DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  1. #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. #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".



    "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
    >
    >
    >
    >
    >



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


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


Sponsored Links