假设我有以下变量:
unsigned long a = 1; //32-bit value
unsigned short b = 1; //16-bit value
unsigned char c ='\x01' //8-bit value
unsigned char buffer[7];
现在我想在缓冲区中映射或组合上面的那些变量,如下所示: 前四个字节应由 int a 的值占用,接下来的 2 个字节由值 b 占用,最后一个字节由 c 占用。
==> buffer = 0x 00000001 0001 01
有没有人知道用 C++ 做这件事的简单方法?目前我有帮助函数返回短裤和整数的字节模式,但我想在 C++ 中一定有更好的方法来做到这一点?
谢谢
最佳答案
使用 union
#include <iostream>
struct MyStructData
{
unsigned long a;
unsigned short b;
unsigned char c;
};
union Swap
{
MyStructData data;
char buffer[7];// Can use [sizeof(MyStructData)]
};
int main()
{
Swap data;
data.data.a = 1;
data.data.b = 1;
data.data.c = 1;
for(int loop=0;loop < 7;++loop)
{
std::cout << "buffer(" << loop <<") = (" << (int)data.buffer[loop] << ")\n";
}
}
关于c++ - 将整数、短裤和字符映射到位模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1209149/