我有一些代码而且我不了解如何取回单个项目:
u32_t foo = ((u32_t)((d) & 0xff) << 24) | ((u32_t)((c) & 0xff) << 16) |
((u32_t)((b) & 0xff) << 8) | (u32_t)((a) & 0xff)
我想输入此转换的结果 我希望这可以将IP地址转换回要显示的部分。 但是当我输入192 168 1 200时,我得到的是0xC801A8C0并且我没有将它转换回来。
有谁知道我如何在union结构中使用项目? 我尝试使用LwIP,但工会结构有问题。我尝试访问local_ip和remote_ip。
答案 0 :(得分:5)
{{1}}
这实际上与上面的代码相反。
答案 1 :(得分:1)
您可以屏蔽foo
u32_t thisWasD = (foo & 0xff000000) >> 24; // ==> will null out the lowest 24 bits
u32_t thisWasC = (foo & 0x00ff0000) >> 16; // ==> will null out the upper 8 and lowest 16 bit
u32_t thisWasB = (foo & 0x0000ff00) >> 8; // ==> etc
u32_t thisWasA = (foo & 0xff) // etc - no shift needed
然后将它们移回去,这样他们就可以在第8位(到24,16,8 - 最后一个已经确定了)
答案 2 :(得分:0)
就像你有一个int input
,你想要按字节和数字分成字节数。将每个字节存储在单独的整数中
int main() {
a = ((uint32_t)((foo) & 0x000000ff) << 24);
b = ((uint32_t)((foo) & 0x0000ff00) << 16);
c = ((uint32_t)((foo) & 0x00ff0000) << 8);
d = ((uint32_t)((foo) & 0xff000000);
}