DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Convert character to binary code

1. Tim Guest

## Convert character to binary code

I'm writing a program that inputs a character and outputs it's binary representation.
The part of the code that does the work is this:

(character & 0x80 ? "1" : "0");
(character & 0x40 ? "1" : "0");
(character & 0x20 ? "1" : "0");
(character & 0x10 ? "1" : "0");
(character & 0x08 ? "1" : "0");
(character & 0x04 ? "1" : "0");
(character & 0x02 ? "1" : "0");
(character & 0x01 ? "1" : "0");

I know the conditional operator is being used here. If the test condition
evaluates to true the program will print a 1, if not the program will print
a 0. What I don't understand is the 0x80 and all the other hex numbers. How
is this mask working? If someone could explain in simple terms I'd appreciate
it.

Tim

2. jonnin Guest

## Re: Convert character to binary code

its hex for positions. binary is from 2^0 to 2^7 in a byte. thats

1 position one ...
2
4
8
16
32
64
128

add all these for a max of 255.

thats what these numbers in hex are.
10 is 16
20 is 32
40 is 64
80 is 128. the rest are the same as decimal ...

anyway, its looking at a single bit of the 8 bits in a byte (char) and if
they are one writes "1" else writes "0".

>
>I'm writing a program that inputs a character and outputs it's binary representation.
>The part of the code that does the work is this:
>
>(character & 0x80 ? "1" : "0");
>(character & 0x40 ? "1" : "0");
>(character & 0x20 ? "1" : "0");
>(character & 0x10 ? "1" : "0");
>(character & 0x08 ? "1" : "0");
>(character & 0x04 ? "1" : "0");
>(character & 0x02 ? "1" : "0");
>(character & 0x01 ? "1" : "0");
>
>I know the conditional operator is being used here. If the test condition
>evaluates to true the program will print a 1, if not the program will print
>a 0. What I don't understand is the 0x80 and all the other hex numbers.

How
>is this mask working? If someone could explain in simple terms I'd appreciate
>it.
>
>Tim
>
>
>
>
>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts

 FAQ Latest Articles Java .NET XML Database Enterprise