繁体   English   中英

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

[英]How to convert an unsigned integer into 32 bit binary representation

到目前为止,这就是我的转换函数所拥有的它采用无符号整数作为参数。 它应该给出这样的结果

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;
}

当然这不是最优的。 相反,我建议使用诸如位移运算符和固定大小的字符数组之类的东西,其中您只需在循环中用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM