C 移位的最高有效位为1
我正在写一个C函数,它从用户那里获取一个数字并将其转换成二进制输出。首先,代码如下:C 移位的最高有效位为1,c,byte-shifting,C,Byte Shifting,我正在写一个C函数,它从用户那里获取一个数字并将其转换成二进制输出。首先,代码如下: void Convert_Number_To_Binary(const int num,char *binary) { double remainder = num; //Start from binary[0] and check if num is divisible by 2^ith power by shifting for(int i = 0; i < 33; i++)
void Convert_Number_To_Binary(const int num,char *binary) {
double remainder = num;
//Start from binary[0] and check if num is divisible by 2^ith power by shifting
for(int i = 0; i < 33; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
printf("i: %d, %d \n", i, (shift) );
//If shift is greater than 0, then remainder is divisible by 2^i
if( (shift & 1) > 0) {
binary[32-i] = '1';
}
else
binary[32-i] = '0';
//printf("i:%d, 32-i:%d\n", i, (32-i));
}
//printf("%c, %c", binary[0], binary[31]);
binary[33] = '\0';
}
对于偶数,前导的“1”不会出现:
num = 16 binary = 000000000000000000000000000010000
我在远程32位linux机器上运行此操作,这可能是原因吗?您应该首先将
int
强制转换为未签名int
,这将强制MSB填充0
大概是这样的:
unsigned int shift = (unsigned int)num >> i;
您正在创建一个33位的二进制字符串,而不是32位:
for(int i = 0; i < 33; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
for(int i = 0; i < 33; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
void Convert_Number_To_Binary(const int num,char *binary) {
//Start from binary[0] and check if num is divisible by 2^ith power by shifting
for(int i = 0; i < 32; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
printf("i: %d, %d \n", i, (shift) );
//If shift is greater than 0, then remainder is divisible by 2^i
if( (shift & 1) > 0) {
binary[32-i-1] = '1';
}
else
binary[32-i-1] = '0';
//printf("i:%d, 32-i-1:%d\n", i, (32-i-1));
}
//printf("%c, %c", binary[0], binary[31]);
binary[32] = '\0';
}