• C

unsigned char * -> bits

I have a  file which contains unsigned char stream . I wish to extract/convert that into
bit stream (0s and 1s )

Could you please suggest an efficient way to do that please  !! ( Suggestion in C++ is also fine )

Who is Participating?
homer99Connect With a Mentor Commented:

in C++


void displayBits(unsigned);

int main()
unsigned x;
char temp1;
cin >> temp1;
return 0;

void displayBits(unsigned value)
unsigned c, displayMask = 1 << 15;

cout<<setw(7)<<value<< " = ";

for(c = 1; c<=16; c++) {
  cout << (value & displayMask ? '1' : '0' );
value <<= 1;

if(c%8 == 0)
  cout << ' ';

in this example a char is read in, the program then performs a bitwise and with 1, which does not affect the char and then the bits are output to the screen.  This is just an example, but it should work.
Let me know

Read in a buffered amount of data (I suggest about 4K at a time to reduce disk access), and then cycle though the data converting the character to there 8-bit string representation.  Do with the conveted string whatever you need.

An old function I had called num2BinString takes a number (or a character), and converts it to the binary representation of the number.

Pass a string to hold the answer (temp in the example), the data to convert (the variable 'a' in the example, and the number of bits to use (for characters, use 8).  Remember that the number of bits to use must be less than the size of the array you are passing in.  For example, if you wanted the binary representation of 16-bit integers, the temp variable would need to be 17 characters in length.

#include <stdio.h>

char* num2BinString(char* s, long n, int c)
unsigned long mask = 1 << (c-1);
int ctr;

for( ctr = 0; ctr < c; ctr++, mask = mask >> 1 )  /* mask/=2 */
    *(s+ctr) = ((n & mask) > 0) ? '1' : '0';
*(s+ctr) = 0; /* NULL TERMINATE */
return s;
} /* num2BinString */

int main()
unsigned char a = 'a';
char temp[9];
num2BinString(temp, (long)a, 8); /* Want 8 bits */
printf("The letter %c is %s\n", a, temp);
return 0;
} /* main */

Here is my solution in C:

#include <stdio.h>

int main(){
    char ch;
    unsigned int x;
    x = 1;
    printf("Enter char to convert to binary: ");
    scanf("%c", &ch);
    x <<= (sizeof(int)*8-1);
    printf("Char %c in binary is: \n", ch);
    while( x ){
        putchar(x & ch ? '1' : '0');
        x >>= 1;
    printf ("\n\n");
    return 0;

Now if you want you could add some error checking or some loop process your stream.
Good Luck!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.