>= -6ren">
gpt4 book ai didi

c - C语言中如何对某些数据进行按位运算?

转载 作者:行者123 更新时间:2023-11-30 21:18:37 25 4
gpt4 key购买 nike

我在 C 函数中有以下代码片段

int i;
for (i = bytes; i>0; --i) {
printf("byte: %d", data & 0xff);
data>>= 8;
}

以大端方式将给定数据拆分为字节(bytesdata 中的字节数)。数据本身可以是任何东西 - 一个 int 或一个 100 字节长的字符串。但是,如果 data 它不是 int,则代码将无法工作(二进制 X 的操作数无效)。

例如,假设 data 是一个内容为 hello world 的字符串,我希望得到以下数字:

byte: 104
byte: 101
byte: 108
byte: 108
byte: 111
byte: 32
byte: 119
byte: 111
byte: 114
byte: 108
byte: 100

我需要一个简单的纯 C 语言的 wotk 解决方案,除了标准库之外,不需要任何额外的库。

最佳答案

如果要打印原始二进制数据的字节:

void print_bytes(const void *data, size_t len)
{
const unsigned char *p = data;
for (size_t i = 0; i < len; i++)
printf("%d ", p[i]);
}

您可以使用任何对象的地址来调用它,如下所示:

unsigned long long u = 1234567890;
print_bytes(&u, sizeof u); // beware of endianness!

const char *s = "hello world";
print_bytes(s, strlen(s));

关于c - C语言中如何对某些数据进行按位运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18255917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com