# Thread: Turning Byte into Binary

1. ## Turning Byte into Binary

Hey guys,

I'm having trouble. I have a byte, and I need to turn it into binary. I know how to mask each individual bit but I don't know how to get that bit. This is what I have so far....

(pseudo code)

Logical AND the byte to get each specific bit. To get the left most bit I AND by 0x80 and that would give me the left most bit's value. I would then shift to the right to bring it to the right most bit.

But I am unsure what to do from here.

Lang

2. You have one bit. So how do you get the next bit? And the next? (Note: This part almost doesn't change.)
You do have to remember that you need to work with the original byte, not the byte after it's been anded and shifted.

3. Search the forums, I have both seen the question asked, and seen it answered (because I have answered it a time or two) before.

4. hmm, I am confused a bit on your question. A byte is really 8 bits, 8 bits in of itself is in binary. For testing printing out a char data type to binary representation you could use a 'printf' statement using the %o specifier.

If you are simply needing to know if a particular bit is set within the byte, then masking is a viable option to test for that.

5. %o is octal, so it's unclear whether that will help OP.

6. Do you mean you want to turn a byte into a string of 1's & 0's like "10010100"?

7. Originally Posted by cpjust
Do you mean you want to turn a byte into a string of 1's & 0's like "10010100"?
That was my understanding of the question. If that is the case, please just search the forum, OP. The question has come up from many, and been answered by quite a few.

8. Assuming you want to turn a number into its binary equivalent:

I've always done it similar to this (probably reinventing the wheel):

number = 255

pseudo-code-ish

Code:
```while (number != 0) {
buffer = (number &#37; 2) & buffer
number /= 2
}
while ((strlen(buffer) % 8) != 0) // pad with zeros
buffer = 0 & buffer```

9. number &#37; 2
number /= 2

using bit operations like & and >> is preffered for bit manipulation