C++访问无符号整数的字节/字的类
union LowLevelNumber
{
unsigned int n;
struct
{
unsigned int lowByte : 8;
unsigned int highByte : 8;
unsigned int upperLowByte : 8;
unsigned int upperHighByte : 8;
} bytes;
struct
{
unsigned int lowWord : 16;
unsigned int highWord : 16;
} words;
};
这个联合允许我访问无符号整数字节或字。 然而,代码看起来相当难看:
var.words.lowWord = 0x66;
有没有一种方法可以让我编写这样的代码:
var.lowWord = 0x66;
更新:
这实际上是关于编写简短/漂亮的代码,如上面的示例所示。联合解决方案本身确实有效,我只是不想每次访问 lowWord 或 lowByte 时都写入 .words 或 .bytes 。
union LowLevelNumber
{
unsigned int n;
struct
{
unsigned int lowByte : 8;
unsigned int highByte : 8;
unsigned int upperLowByte : 8;
unsigned int upperHighByte : 8;
} bytes;
struct
{
unsigned int lowWord : 16;
unsigned int highWord : 16;
} words;
};
This union allows me to access the unsigned integer byte or word-wise.
However, the code looks rather ugly:
var.words.lowWord = 0x66;
Is there a way which would allow me to write code like this:
var.lowWord = 0x66;
Update:
This is really about writing short / beautiful code as in the example above. The union solution itself does work, I just don't want to write .words or .bytes everytime I access lowWord or lowByte.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++
将 http://www.cplusplus.com/reference/stl/bitset/ 满足您的需求?
纯 C 版本看起来像这样:
这可能比编写自定义类/联合更易于维护,因为它遵循典型的 C 习惯用法。
C++
Would http://www.cplusplus.com/reference/stl/bitset/ serve for your needs?
Plain C version would look something like this:
This is probably going to be more maintainable down the road than writing a custom class/union, because it follows the typical C idiom.
你可以制作
如果你不关心括号,
并使用它。或者您可以选择
后
一种技术是 C++ 中已知的属性模拟。
You can make
and use it if you don't care parenthesis.
Or you can go fancy
and then
The latter technique is a known property emulation in C++.
您可以轻松地将其包装在一个类中并使用 get/set 访问器。
You could easily wrap that in a class and use get/set accessors.
为此使用联合是不好的,因为它不可移植于字节顺序。
使用访问器函数并通过位掩码和移位来实现它们。
Using a union for this is bad, because it is not portable w.r.t. endianness.
Use accessor functions and implement them with bit masks and shifts.
请注意删除的
bytes
和words
名称。Note the removed
bytes
andwords
names.