C program to read and write hexadecimal values

C program to read and write hexadecimal values:

Hexadecimal values are base 16 number system. Numbers from 0 to 9 and characters from A to F are used to represent a hexadecimal value. If we represent decimal values in hexadecimal, 10 will be A, 11 will be B etc. In this post, we will learn how to save hexadecimal values in variables in C and how to print hexadecimal values.

Storing hexadecimal in variables:

For hexadecimal, we don’t have any specific data types. But we can store it in the integral data types in C. Hexadecimal values are preceding with 0x or 0X. For example hexadecimal value 3E8 is represented as 0x3E8.

To print hexadecimal values, we can use either %x or %X. %x is used for lower case i.e. a to f and %X is used for upper case i.e. A to F.

We can use the same format specifiers %x or %X to read hexadecimal values using scanf.

Example program:

#include <stdio.h>

int main()
{
    int first_value;
    int second_value = 0x3E8;

    printf("Enter value for first_value:\n");
    scanf("%x", &first_value);

    printf("first_value: %x or %X\n", first_value, first_value);
    printf("second_value: %x or %X\n", second_value, second_value);
}

It will print output like below:

Enter value for first_value:
3e8
first_value: 3e8 or 3E8
second_value: 3e8 or 3E8

We are using scanf and printf with hexadecimal values in this example. We are also using %x and %X to print the values in both formats.

If we use %d, it will print its decimal value. For example:

#include <stdio.h>

int main()
{
    int first_value;
    int second_value = 0x3E8;

    printf("Enter value for first_value:\n");
    scanf("%x", &first_value);

    printf("first_value: %d\n", first_value, first_value);
    printf("second_value: %d\n", second_value, second_value);
}

This program will print:

Enter value for first_value:
3e8
first_value: 1000 or 3E8
second_value: 1000 or 3E8

Decimal representation of 3E8 is 1000

You might also like: