使用union中内嵌struct这种方法,可以打包和解析数据
#include<iostream> using namespace std; //用来解析 // bit-field used to unpack the st_mode in field in a _stat structure struct modes { unsigned others : 3; // permissions for everyone else unsigned group : 3; // group permissions unsigned user : 3; // file owner permissions unsigned type : 7; // other file data - directory or regular file? }; //在16bit和mode 位间映射 union map // used to map between a 16-bit int and a mode bit field. { unsigned short statmode; // data input as 16-bit int 已16-bit输入 modes convert; // data output as modes bit field. 位域输出 }; int main() { map mapper; //存储16-bit整数到mapper的statmode域 //store a 16-bit integer into the mapper‘s statmode field mapper.statmode =0x88; //read the unpacked information out of the mapper‘s convert field, which further divides the data into bit-fields //从mapper转换域读解析信息,然后分数据到位域 cout << mapper.convert.user << endl; cout << mapper.convert.group << endl; cout << mapper.convert.others << endl; }
原文:https://www.cnblogs.com/beepeg/p/14421956.html