Creating string representation of unsigned char bits

Hello, I need to convert the bit representation of an unsigned char into a string.

so like 254 would be "11111111"
I'm having some trouble where no matter what number I try to convert I get 01111111.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string bin2string(unsigned char N) { 
  string sN(8,'0');
  unsigned char X;  
  unsigned char Y = 0;

  for(int i = 0; i < 8; i++){
    X = N >> i;
    if(X == Y)
      sN[7-i] = '0';
    else 
      sN[7-i] = '1';
  }
    cout << sN << endl;
  return sN;
}
1
2
3
4
5
6
7
#include <bitset>
#include <string>
#include <limits>

std::string bin2string( unsigned char N ) {
      return std::bitset< std::numeric_limits<unsigned char>::digits >(N).to_string() ;
}
so like 254 would be "11111111"


Actually, 254 would be "11111110".
Yes, Thank you doug.

JLBorges, thank you but I have to do it this way, I was hoping someone could point me out to where I was wrong.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include <limits>

std::string bin2string( unsigned char N ) {

    std::string aN( /*8*/ std::numeric_limits<unsigned char>::digits, '0' ) ;

    for( std::size_t pos = aN.size() - 1 ; N > 0 ; --pos )
    {
        aN[pos] = N%2 ? '1' : '0' ;
        N /= 2 ;
    }

    return aN ;
}
Topic archived. No new replies allowed.