gpt4 book ai didi

c - gcc 按位奇数行为

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:29 24 4
gpt4 key购买 nike

我在久违后回到 C,我正在尝试学习按位运算符。我写了这个小程序来证明我的困惑。第一个 printf 有效(在标题之后),但第二个无效。这是某种操作顺序还是什么?

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

const char *byte_to_binary(int x)
{
static char b[9];
b[0] = '\0';

int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}

return b;
}

int main(int argc, char *argv[])
{
unsigned int ch = atoi(argv[1]);
unsigned int a = atoi(argv[2]);
int chA;
int chB;
int chC;
int chD;
int chE;
int chF;
chA = ch & a;
chB = ch | a;
chC = ch ^ a;
chD = ~ch;
chE = ch << 2;
chF = ch >> 2;
char chAS[16];
char chBS[16];
char chCS[16];
char chDS[16];
char chES[16];
char chFS[16];
strcpy(chAS, byte_to_binary(chA));
strcpy(chBS, byte_to_binary(chB));
strcpy(chCS, byte_to_binary(chC));
strcpy(chDS, byte_to_binary(chD));
strcpy(chES, byte_to_binary(chE));
strcpy(chFS, byte_to_binary(chF));

printf("[c][%%d ][%%o ][%%x][ %%s ][ & ][ | ][ ^ ][ ~ ][ << ][ >> ]\n");
printf("[%c][%03d][%03o][%02x][%s][%s][%s][%s][%s][%s][%s]\n", isprint(ch) ? ch : ' ', ch, ch, ch, byte_to_binary(ch), chAS, chBS, chCS, chDS, chES, chFS);
printf("[%c][%03d][%03o][%02x][%s][%s][%s][%s][%s][%s][%s]\n", isprint(ch) ? ch : ' ', ch, ch, ch, byte_to_binary(ch), byte_to_binary(ch & a), byte_to_binary(ch | a), byte_to_binary(ch ^ a), byte_to_binary(~ch), byte_to_binary(ch << 2), byte_to_binary(ch >> 2));

return (0);
}

最佳答案

您的byte_to_binary 函数返回一个指向静态数组的指针。然后您调用 printf,多次传递此函数的返回值,并且每次调用都返回相同 指针,因此无论哪个函数调用碰巧最后出现都将是在所有情况下打印结果的那个。

您需要拆分您的 printf 调用以便每次只调用一次 byte_to_binary,或者将结果复制到临时文件中并打印它们。您在第二个 printf 调用中执行后者,因此只需使用它并删除第三个。

关于c - gcc 按位奇数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53525111/

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