hex to dec to binary

This is a discussion on hex to dec to binary within the C Programming forums, part of the General Programming Boards category; Hi! Can anyone tell me how to convert from hex to binary(8bit and 16 bit). Also I want a convertsion ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    5

    hex to dec to binary

    Hi!
    Can anyone tell me how to convert from hex to binary(8bit and 16 bit).
    Also I want a convertsion from dec to binary.
    Binary back to hex.
    I am writing an assembler and I need some function to accomplish this.Are there any c library functions?
    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Miami, FL
    Posts
    6
    You can use ultoa to get them into string format.

    http://www.cplusplus.com/ref/cstdlib/ultoa.html

    I'm not aware of any library functions that do the conversions directly. They wouldn't be too hard to write yourself though.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    You can use sprintf or printf to convert to a hex string, and strtoul or strtol to convert a hex string to an int.
    Code:
       unsigned int num = 0xffffffff;
       char hex_str[33];
       
       sprintf(hex_str, "%X", num);
       printf("%s\n", hex_str);
       
       num = strtoul(hex_str, NULL, 16);
       printf("%X\n", num);
    There's no standard library functions to convert a number to a binary string. It's easy to write your own by using bit shifting and masking.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 18
    Last Post: 03-26-2008, 10:01 AM
  2. Replies: 11
    Last Post: 03-24-2006, 11:26 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Is binary HEX?
    By Budgiekarl in forum Tech Board
    Replies: 11
    Last Post: 11-23-2003, 09:02 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21