gpt4 book ai didi

c++ - 如何将 unsigned int 转换为 unsigned char 数组

转载 作者:太空狗 更新时间:2023-10-29 23:39:43 24 4
gpt4 key购买 nike

我只需要使用按位 & 运算符提取这些字节。 0xFF 是提取一个字节的十六进制掩码。对于 2 个字节,此代码可以正常工作:

#include <stdio.h>

int main()
{
unsigned int i = 0x7ee;
unsigned char c[2];

c[0] = i & 0xFF;
c[1] = (i>>8) & 0xFF;

printf("c[0] = %x \n", c[0]);
printf("c[1] = %x \n", c[1]);


return 0;
}

输出:

c[0] = ee;
c[1] = 7;

我应该怎么做才能使 4 个字节正常工作?

unsigned int i = 0x557e89f3;
unsigned char c[4];

我的代码:

unsigned char c[4];
c[0] = i & 0xFF;
c[1] = (i>>8) & 0xFF;
c[2] = (i>>16) & 0xFF;
c[3] = (i>>24) & 0xFF;
printf("c[0] = %x \n", c[0]);
printf("c[1] = %x \n", c[1]);
printf("c[2] = %x \n", c[2]);
printf("c[3] = %x \n", c[3]);

最佳答案

#include <stdio.h>

int main()
{
unsigned int i = 0x557e89f3;
unsigned char c[4];

c[0] = i & 0xFF;
c[1] = (i>>8) & 0xFF;
c[2] = (i>>16) & 0xFF;
c[3] = (i>>24) & 0xFF;

printf("c[0] = %x \n", c[0]);
printf("c[1] = %x \n", c[1]);
printf("c[2] = %x \n", c[2]);
printf("c[3] = %x \n", c[3]);


return 0;
}

关于c++ - 如何将 unsigned int 转换为 unsigned char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30840575/

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