-
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
-
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".
"Tim" <tkangas@uslink.net> wrote:
>
>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
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks