gpt4 book ai didi

c - 无法从整数中正确提取字节

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:08 25 4
gpt4 key购买 nike

我编写的程序适用于某些整数值但不适用于所有...为什么??

程序输出

int value is abcdef78
first byte is 78 addr is 2686741
second byte is ffffffef addr is 2686742
third byte is ffffffcd addr is 2686743
fourth byte is ffffffab addr is 2686744

预期输出

int value is abcdef78
first byte is 78 addr is 2686741
second byte is ef addr is 2686742
third byte is cd addr is 2686743
fourth byte is ab addr is 2686744

Process returned 0 (0x0) execution time : 0.015 s
Press any key to continue.

代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{

int i=0xabcdef78;
int *ip;

printf("int value is %x\n",i); // *ip contents of address

char c;
char *cp;
cp=&i;
c = *cp;
printf("first byte is %x addr is %d\n",*cp++,cp);
printf("second byte is %x addr is %d\n",*cp++,cp);
printf("third byte is %x addr is %d\n",*cp++,cp);
printf("fourth byte is %x addr is %d\n",*cp++,cp);

return 0;
}

最佳答案

原因是您的 char 被提升为带符号扩展的 int。二进制形式的 0xef 是:

1110 1111

它被提升为 32 位整数,带有如下符号扩展:

1111 1111  1111 1111  1111 1111  1110 1111

而二进制形式的 0x78 是:

0111 1000

最高有效位是 0,所以它像这样被提升:

0000 0000  0000 0000  0000 0000  0111 1000

有两种解决方法:

  1. 不要将 char 打印为 32 位值,即使用 %hhx 而不是 %x。

  2. 使您的 char 无符号,即 unsigned char *cp 而不是 char *cp

关于c - 无法从整数中正确提取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175638/

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