【问题标题】:Bitwise complement operator (~) not working at a point in C按位补码运算符 (~) 在 C 中的某个点不起作用
【发布时间】:2021-01-04 14:51:02
【问题描述】:

此代码采用 2 字节 int 并交换字节。

为什么我评论的这段代码似乎不起作用?

输入/输出

*当我输入 4 时,预期输出为 1024,而在通过该行后,第 9 位到第 16 位全部设置为“1”。

*然后我尝试输入 65280,其预期输出为 255,而不是输出 65535(将所有 16 位设置为“1”

#include<stdio.h>

int main(void)
{
    short unsigned int num;
    printf("Enter the number: ");
    fscanf(stdin,"%hu",&num);
    
    printf("\nNumber with no swap between bytes---> %hu\n",num);
    
    unsigned char swapa,swapb;
    swapa=~num;
    num>>=8;
    swapb=~num;
    
    num=~swapa;
    num<<=8;
    num=~swapb;  //this line is not working why
    
    printf("Swaped bytes value----> %hu\n",num);
}

【问题讨论】:

    标签: bit-manipulation bitwise-operators


    【解决方案1】:

    Integral promotions 也是num 的当前值被注释行破坏了,可能需要|=+=^=

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多