如果给我一个大小为 8 的 char 数组,其中我知道前 3 个字节是 id,下一个字节是消息,最后 3 个字节是值。我如何使用位操作来提取消息。
示例:一个 char 数组包含 9990111(每个位置一个整数),其中 999 是 id,0 是消息,111 是值。
有什么建议吗?谢谢!
最佳答案
给定:
the array contains {'9','9','9','0','1','1','1'}
然后您可以使用sscanf()
进行转换:
char buffer[8] = { '9', '9', '9', '0', '1', '1', '1', '\0' };
//char buffer[] = "9990111"; // More conventional but equivalent notation
int id;
int message;
int value;
if (sscanf(buffer, "%3d%1d%3d", &id, &message, &value) != 3)
…conversion failed…inexplicably in this context…
assert(id == 999);
assert(message == 0);
assert(value == 111);
但是那里不需要位操作。
关于c - C中字符数组的位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509313/