简体   繁体   中英

Bit patterns in c++

I'm trying to output the bit patterns from 0-130, but somehow i'm just getting upside down question marks where the corresponding bit pattern should be . The way the code should look is below. Any suggestions?

include <iostream>
using namespace std;

int isSet( unsigned int x, int i );
string bitsetfn(unsigned x, int nbits);

int main() {
  for (int counter = 0; counter <=130; counter++){
    cout << counter << " is: " << bitsetfn(counter,16)<<endl;
  }
  return 0;
}

string bitsetfn(unsigned x, int nbits){
  string s=" ";
  for(int j=0; j<nbits; j++) {    
    s+=isSet(x,j);
  }
  return s;
}

int isSet( unsigned int x, int i ) {
  return ((x >> i) & 1);
}

This is what the output should look like...

0 is: 0000000000000000 
1 is: 0000000000000001 
2 is: 0000000000000010 
3 is: 0000000000000011 
4 is: 0000000000000100 
5 is: 0000000000000101 
6 is: 0000000000000110 
7 is: 0000000000000111 
8 is: 0000000000001000 
9 is: 0000000000001001
10 is:0000000000001010 
11 is: 0000000000001011

Suggestion 1: You can use an ostringstream to build up your string.

string bitsetfn(unsigned x, int nbits){
  ostringstream oss;
  for(int j=0; j<nbits; j++) {    
    oss << isSet(x,j);
  }
  return oss.str();
}

Suggestion 2: You can convert the integer value of the binary digit into its equivalent character encoding. The decimal digits in the character encoding are required to be sequential and contiguous starting from '0' , so:

  s+=isSet(x,j) + '0';

will append either a '0' or a '1' .

Suggestion 3: Use a bitset :

#include <iostream>
#include <bitset>
using namespace std;

int main() {
  for (int counter = 0; counter <=130; counter++){
    cout << counter << " is: " << bitset<16>(counter)<<endl;
  }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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