GIDNetwork > Conversion: Binary, Decimal, Hexadecimal
« Pausing a Program PHP function to ping Google Sitemaps »

Conversion: Binary, Decimal, Hexadecimal

by: WaltP - Aug 28, 2005

To Convert Or Not To Convert. That is the Question.

One of the big questions I see on GIDForums is, How do I convert decimal to hex? Once you understand the difference between the computer's use of binary, decimal, and hexadecimal you'll understand why the question as asked is a non-question. It's like asking the difference between ice and frozen water.

Conversion? We Don't Need No Stinkin' Conversion.

First of all, the computer talks in binary only. Integers, floating point, characters, strings -- they are all binary. In order for us humans to understand this binary, a simpler representation is required than a sequence of 1's and 0's. Hence we have output in decimal, hex, and character (I will ignore floating point simply because it's more of the same. These other formats are enough to get the concept). The one who asks the question generally is asking how to output a variable (binary) in hex (character string).

For example, if you have the 8 bit binary value 01011010 it's hard for us to interpret it. So the compilers have some built-in functions to display the binary in other formats. In this case the binary value is absolutely equivalent to 90d (decimal), 5Ah (hexadecimal), the character Z. These 'conversions' are simply an alternate way to display this binary value. There's no conversion going on from our standpoint. It's taken care of internally. Binary output though is not standard and this must be generated by the user. See example program below.

So bottom line, there are no conversions necessary for normal programming. Just choose the appropriate output format for the variable and it's contents. The reverse is true for input.

When you really need it, it's good to know

The main place where a conversion is necessary is when you must translate a string of characters (usually as input) into it's binary internal value or vice versa. There are many routines that already handle this for us:

  • binary to string:

    • printf()

    • sprintf()

    • strstream

    • others

  • string to binary:

    • scanf()

    • sscanf()

    • atoi(), atol()...

    • strtol

    • strstream

    • others

These functions above for the most part should handle 90% of the conversion needs. But sometimes that extra 10% is needed. So, though not an algorithmic explanation, the following should give you an idea about how the concept works.

If we have a string of characters representing the decimal value "143", we in fact have 3 characters '1', '4', '3', or in binary: 00110001, 00110100, 00110011.

We need to convert these characters into binary values: 00000001, 00000100, 00000011. Notice the difference between the binary character and the binary value is 00110000, or the character '0'/48d/30h. Therefore, all we need to do is subtract a 48d from each character, giving us the binary values 1, 4, and 3. Now just assemble the separate values into the single binary: (1* ( 10 * 10 )) + (4* (10) ) + (3* (1) ).

This technique works for any base from binary on up. For example,

  • Binary: "1101" in binary gives us 1, 1, 0, 1 after the subtraction. Assemble using:
    (1* ( 2 * 2 * 2 )) + (1* ( 2 * 2 )) + (0* (2) ) + (1* (1) )

  • Octal: "3721" => 3, 7, 2, 1 =>
    (3* ( 8 * 8 * 8 )) + (7*( 8 * 8 )) + (2* ( 8 ) ) + (1* (1) )

The only difference for any base above 10 is the initial subtraction may not be quite accurate. Take the hex value "5D3". The initial subtraction yields 5, 20, 3. 20 is obviously not correct. For any values above 9, we must additionally subtract 7. This is to take into account the 7 characters between '9' and 'A' in the ASCII character chart. This now gives 5, 13, 3 (Dh == 13d).
Assemble: (5* ( 16 * 16 )) + (13* (16) ) + (3* (1) ).
We now have the binary representation of the character input.

One further point -- if the letter in the hex value is lower case,
subtract an additional 32 ('a' - 32 => 'A').

Convert a numeric string into it's internal binary value

C/CPP/C++ Code Example:

// This program will convert a string value into it's internal 
// binary equivalent for any base up to 36. The conversion will 
// stop at the first invalid character for the base specified 
// (which includes the \\n or \\0)

#include <stdio.h>
int Convert(char *, int);

int main()
    char inbuf[32];
    int  base;      // Base for the conversion
    int  binary;    // final binary value
    int  j;         // loop counter

    printf("Enter the base (in decimal): ");
    fgets(inbuf, 32, stdin);    // Get the base for conversion
    sscanf(inbuf,"%d",&base);   // Make it a value

    printf("Enter the base %d value to convert: ", base);
    fgets(inbuf, 32, stdin);    // Get the value for conversion

    binary = Convert(inbuf, base);
    printf("%d  %Xh \n", binary, binary);  // output dec & hex
    return 0;
int Convert(char *buf, int cbase)
    int j;
    int bin;
    j = 0;
    bin = 0;                 // start the binary value at 0
    while (buf[j])
        buf[j] -= 48;           // convert character for binary
        if (buf[j] > 16)
            buf[j] -= 7;        // character was probably letter
        if (buf[j] >= cbase)
            buf[j] -= 32;       // character was probably lower 
        if (buf[j] >= cbase || buf[j] < 0)
            break;              // invalid character, done
        bin *= cbase;           // multiply by the base 
        bin += buf[j];          // add current value
        j++;                    // next character
    return bin;             // return the binary value

To go from binary to the character string you should be able to convert the above program to start with binary and create a string. The modulus % operator is helpful.

Convert an internal binary value into a binary string

C/CPP/C++ Code Example:

// Converts a binary (internal) 32 bit value into a character 
// string to output the binary representation

#include <stdio.h>
void Convert(int, char*);   

int main()
    int  binary;
    char string[33];    // assuming 32bit integers
    printf("Enter a number: ");
    scanf("%d", &binary);

    Convert(binary, string);   
    printf("%s  %d  %Xh \n", string, binary, binary);
    return 0;

void Convert(int bin, char *str)
    unsigned int mask;      // used to check each individual bit, 
                            //    unsigned to alleviate sign 
                            //    extension problems

    mask = 0x80000000;      // Set only the high-end bit
    while (mask)            // Loop until MASK is empty
        if (bin & mask)     // test the masked bit
              *str = '1';   // if true, value is 1
              *str = '0';   // if false, value is 0
        str++;              // next character
        mask >>= 1;         // shift the mask 1 bit
    *str = 0;               // add the trailing null 

So conversions are actually only necessary when converting from character string to binary or vice versa. So to convert from hex to decimal implies you have a character string in hex and you want a character string in decimal -- 90% of the time not what is needed. But if it is, first convert to internal binary then back to string.

Would you like to comment? This story has been viewed 80,400 times.
« Pausing a Program PHP function to ping Google Sitemaps »


Copyright © GIDNetwork™ 2001 - 2024

Another website by J de Silva

Page generated in : 0.00655 sec.