Convert a number to hex

I am not trying to cast a spell on you. What I am going to write is how to convert a decimal number into hexadecimal in C language.

int a = 100;
printf("%x",a);

 So printf format specifier %x will print a value in hex. %o (oh not zero) will print the value in octal.

Is it that simple. It is simple. Do you also know that you can directly type your hex values to variables. And octal too.

int m = 0xff; //255
int n = 011;//octal - 9

So you type a number with prefix zero - it is treated as octal number. And prefix 0x - it is treated as hexadecimal.

One small program to end the post.


#include<stdio.h>
int main()
{
    int n;
    while (1)
    {
    printf("Enter a number: (-1 to quit)");
    scanf("%d",&n);
    if(n==-1)
       break;
    printf("%4d    %4o    %4x\n",n,n,n);
    }
}

The program prints numbers in decimal, octal and hexadecimal continuously until -1 is entered. 

By the way, in C++, you need to use io manipulator hex and oct to print the numbers in hexadecimal and octal.

Liked this post? You will get plenty of such questions in my app C interview questions

Comments

Popular Posts