如何将无符号整数转换为32位二进制表示



到目前为止,这就是我的转换函数它采用一个无符号整数作为参数。它应该给出类似的结果

outputBinary(1) //=> 0000 0000 0000 0000 0000 0000 0000 0001
outputBinary(5) //=> 0000 0000 0000 0000 0000 0000 0000 0101
outputBinary(1000000) //=> 0000 0000 0000 1111 0100 0010 0100 0000
void outputBinary(unsigned int x){
int temp = x;
int remain;
string binary = "";
while(temp != 0){
remain = temp%2;
binary = binary + to_string(remain);
temp = temp/2;
}
cout << binary << endl;
}

首先,如果您想要32位表示,请使用uint32_t作为函数的类型输入。

其次,而不是:

while(temp != 0){
remain = temp%2;
binary = binary + to_string(remain);
temp = temp/2;
}

写一些类似的东西

for(int i=0;i<32;++i){
remain = temp%2;
binary = to_string(remain).append(binary);
temp = temp/2;
}

当然,这不是最优的。相反,我建议使用类似于移位运算符和固定大小的char数组的方法,在循环中只需将字符替换为0或1。

如果您想打印所有的"前导";零,则不能使用while(temp != 0){。你必须确保准确地循环32次。for循环可用于此。

此外,使用uint32_t来确保输入具有32位。

类似:

void outputBinary(uint32_t x){
std::string binary = "";
for(int i = 0; i < 32; ++i){
if (i % 4 == 0) binary = " " + binary;
binary = std::to_string(x % 2) + binary;
x = x/2;
}
std::cout << binary << std::endl;
}

如果像outputBinary(1000000);一样调用,则输出为:

0000 0000 0000 1111 0100 0010 0100 0000

最新更新