从十六进制获取 LSB 的值(C 代码)
我在 C 中有这样的代码:
unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07};
我需要提取它,以便最终值是:
0xa1df7
如果十六进制值至少有 1 个零,我只能提取并使其工作:
unsigned char const data[ ] = {0x0a, 0xd0, 0xf0, 0x07};
使用下面的代码:
for(int i = 0; i < SIZE; ++i)
{
tmp = data[i];
if ( (data[i] <= 0x0F) && (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0)) // one of the hex is zero
{
tmp = ((tmp << 4) >> 4) << N[i];
std::cout << "foo: " << std::hex << tmp << ":" << std::endl;
}
else if ((data[i] >= 0x0F) && (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0) )
{
tmp = (tmp >> 4) << N[i];
std::cout << "bar: " << std::hex << tmp << ":" << std::endl;
}
else
{
std::cout << "result: " << std::hex << result << ":" << std::endl;
std::cout << "tmp << 8: " << std::hex << (tmp << 8)<< ":" << std::endl;
result = result | (tmp << 8);
std::cout << "result |= (tmp << 8): " << std::hex << result << ":" << std::endl;
}
result |= tmp;
std::cout << "boo: " << std::hex << result << ":" << std::endl;
}
看来最后一个 else {...} 块对我来说很麻烦。有什么想法吗?谢谢!
I've got a code like this in C:
unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07};
I need to extract it such that the final value is:
0xa1df7
I have only been able to extract and get it working if the hex values that have at least 1 zero:
unsigned char const data[ ] = {0x0a, 0xd0, 0xf0, 0x07};
using the code below:
for(int i = 0; i < SIZE; ++i)
{
tmp = data[i];
if ( (data[i] <= 0x0F) && (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0)) // one of the hex is zero
{
tmp = ((tmp << 4) >> 4) << N[i];
std::cout << "foo: " << std::hex << tmp << ":" << std::endl;
}
else if ((data[i] >= 0x0F) && (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0) )
{
tmp = (tmp >> 4) << N[i];
std::cout << "bar: " << std::hex << tmp << ":" << std::endl;
}
else
{
std::cout << "result: " << std::hex << result << ":" << std::endl;
std::cout << "tmp << 8: " << std::hex << (tmp << 8)<< ":" << std::endl;
result = result | (tmp << 8);
std::cout << "result |= (tmp << 8): " << std::hex << result << ":" << std::endl;
}
result |= tmp;
std::cout << "boo: " << std::hex << result << ":" << std::endl;
}
It seems the last else {...} block is troublesome for me. Any ideas? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
输出“a1df7”
outputs "a1df7"
您最好先将其全部转换为十六进制字符串(“0a1df007”),然后删除所有零:)
You'd better convert it all to a hex string first ("0a1df007") and then delete all zeroes :)
嗯,但这看起来像是一个简单的网络字节顺序。
对于 32 位 int,请执行以下操作:
对于 64 位值,执行类似操作。
PS 注意标志。在某些情况下,需要显式转换为有符号类型才能强制符号位扩展。
Uhm, but that looks like a plain network byte order.
For 32bit int, do something like:
And similarly for 64bit values.
P.S. Be careful about sign. In some cases explicit conversion to a signed type is required to force sign bit extension.