Re: [問題] Byte資料個別定義

看板C_and_CPP (C/C++)作者 (克里斯)時間16年前 (2009/04/03 02:15), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
感覺有點殺雞用牛刀的感覺 看一看笑一笑就好了 #include <iostream> #include <bitset> #include <iomanip> #include <ctime> using namespace std; template <typename T> class bitfieldtest { public: T data; enum mask {mx = 0xC000, mo = 0x3FE0, mw = 0x0018, ma = 0x0006, me = 0x001}; enum shift {sx = 14, so = 5, sw = 3, sa = 1, se = 0}; typedef bitfieldtest<T> this_type; public: inline bitfieldtest(const T& d = T()): data(d) {} inline T Get(const mask& m, const shift& s) { return (data&m) >> s; } inline this_type& Clear(const mask& m) { data &= ~m; return *this; } inline this_type& Set(const T& v, const mask& m, const shift& s) { Clear(m); data |= ((v & (m >> s)) << s); return *this; } }; int main(int argc, char *argv[]) { srand((unsigned int)time(NULL)); bitfieldtest<unsigned int> ta(rand()); cout << "xxooooooooowwaae" << endl << hex; cout << bitset<16>(ta.data) << " " << setw(4) << ta.data << endl; cout << setw(16) << bitset<16>(ta.mo) << endl; unsigned int o = ta.Get(ta.mo, ta.so); // 取得 o 欄位 cout << setw(11) << bitset<9>(o) << endl; cout << endl; ta.Set(100, ta.mo, ta.so); // 設定 o 欄位 = 100 cout << bitset<16>(ta.data) << " " << setw(4) << ta.data << endl; cout << setw(16) << bitset<16>(ta.mo) << endl; system("pause"); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.195.88.23 ※ 編輯: chrisdar 來自: 123.195.88.23 (04/03 02:16)
文章代碼(AID): #19rG2-el (C_and_CPP)
文章代碼(AID): #19rG2-el (C_and_CPP)