1

If I have a character array and I want to obtain the 8 bit binary representation of each of the characters, how do I do that? I could only obtain the integer values, but do not know how to make the char or its integer ascii value into 8 bits.

Thank you!

Iris Lim
  • 19
  • 2
  • 2
    A `char` is already an 8 bit value. So it is not clear what you mean. Can you please show some code example of what you are trying to do? – kaylum Jan 23 '20 at 05:12
  • For each char `c` where `(' ' <= c <= '~')` you can output the binary representation with `for (i = CHAR_BIT - 1; i >= 0; i--) putchar ((c >> i) & 1 ? '1' : '0'); putchar ('\n');` You will need to include `limits.h` for `CHAR_BIT`. – David C. Rankin Jan 23 '20 at 05:40

2 Answers2

0
char number = something;
char bits[8];
for (int i = 0; i < 8; i++)
{
    bit[i] = (number >> i) & 1;
}

This shifts the number right by i positions (>>), so that each bit in the number gets moved to the rightmost position.

Then does an AND (&) with 1, which sets everything else to 0. (1 in binary has zeros everywhere except the rightmost position)

If you want to print the 8 bit representation, you add this inside the loop:

printf("%d", bits[i]);
0

If I have a character array

unsigned char charBuff[5] = {'a','b','c','d', '\0'};

and I want to obtain the 8 bit binary representation of each of the characters, how do I do that?

To print the binary equivalent of each char of the array, you can follow below steps

Step-1 : Find the number of elements in the given char array

unsigned char charBuff[5] = {1,2,3,4};
unsigned int numElem = sizeof(charBuff) / sizeof(charBuff[0]);

Step-2 : Rotate a loop till numElem times. For e.g

for(index = 0; index < numElem; index++)
{
}

Step-3: select each char array index & implement the functionality to get the binary equivalent of each char in the array.

for(index = 0; index < numElem; index++)
{
    /* select charBuff[index] and charBuff[index] is a single char i.e it can only 8 bits hence rotate inner loop 8 times */
    for(subIndex = 0; subIndex < 8; subIndex++)
    {
        printf("%d", (charBuff[index]) >> subIndex & 1); /* it prints 0 or 1 */
    }

    printf(" "); /* Optional : print white space for readability after printing binary equivalent of charBuff[index] */
 }
Achal
  • 11,821
  • 2
  • 15
  • 37