C - Data Type hexadecimal integer

Introduction

Hex is short for hexadecimal, which is the base 16 counting system.

The following table shows the 16 hexadecimal values 0 through F and how they relate to four bits of data.

Hex
Binary
Decimal
Hex
Binary
Decimal
0x0
0000
0
0x8
1000
8
0x1
0001
1
0x9
1001
9
0x2
0010
2
0xA
1010
10
0x3
0011
3
0xB
1011
11
0x4
0100
4
0xC
1100
12
0x5
0101
5
0xD
1101
13
0x6
0110
6
0xE
1110
14
0x7
0111
7
0xF
1111
15

The hexadecimal values shown are prefixed with 0x.

The next hexadecimal value after 0xF is 0x10.

It's the value 16 in decimal (base 10).

For binary value 10110100, first splits it into two 4-bit nibbles: 1011 0100.

Then the code translates it into hex.

The C programming language does the translation as well, as long as you use the %x or %X conversion characters.

Demo

#include <stdio.h> 

char *to_binary(int n); 

int main() //from  w w w  . j av  a 2s .  c o  m
{ 
    int b,x; 

    b = 21; 

    for(x=0;x<8;x++) 
    { 
        printf("%s 0x%04X %4d\n",to_binary(b),b,b); 
        b<<=1; 
    } 

    return(0); 
} 

char *to_binary(int n) 
{ 
    static char bin[17]; 
    int x; 

    for(x=0;x<16;x++) 
    { 
        bin[x] = n & 0x8000 ? '1' : '0'; 
        n <<= 1; 
    } 
    bin[x] = '\0'; 
    return(bin); 
}

Result

Related Topic