簡體   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