Search code examples
byteoutputbit-shiftputchar

C++ Output a Byte Clarification


From textbook:

enter image description here

So I know a byte has 8 bits and the right bit-shift adds zero bits to the left and pops off bits from the right. But how is it used the above example to output a byte? I would've expected:

putchar(b >> 8)
putchar(b >> 7)
putchar(b >> 6)
etc.

Since I assume putchar outputs the popped off bits?


Solution

  • putchar prints the ascii character corresponding to the integer given.

    putchar(0x41) converts the integer 0x41 into an unsigned char (with a size of one byte) and prints out the ascii character corresponding to 0x41 (which is "A").

    The key thing to realize here that putchar only looks at the lower 8 bits, i.e. putchar(0x41) and putchar(0xffffff41) do the same thing.

    Now let's look at what happens when you pass something to your function above.

    outbyte(0x41424344);

    first it bitshifts b by 24 bits, and then calls putchar on that value 0x41424344 << 24; //0x00000041 putchar(0x00000041); //A

    then it bitshifts b by 16 bits, and then calls putchar on that value 0x41424344 << 24; //0x00004142 putchar(0x00004142); //B

    etc.

    Here it is in action: http://ideone.com/3xeFSx