Hexadecimal integers are frequently used in computing for expressing binary values in a more comprehensible way. Base-16 numbers known as hexadecimal numbers are widely used in a variety of programming languages, including C. We will go through how to read and write hexadecimal values and also elaborate on it using C programs for better understanding.
What is a Hexadecimal Value in C?
A hexadecimal value in the C programming language is a base-16 formatted number. Binary values are often represented in a more readable way using hexadecimal numbers.
Hexadecimal numbers are composed of the digits 0 through 9 and the letters A through F (or a-f), where each digit represents a number between 0 and 15. The numbers 10 to 15 are denoted by the letters A to F.
In C, hexadecimal numbers are denoted by a prefix "0x" or "0X" preceding the digits. For example, the following syntax can assign the hexadecimal value 0x3F to an integer variable:
int hexadecimal_value = 0x3F;
Additionally, we can print a hexadecimal value to our console using the printf() function and "%x" format specifier:
int hexadecimal_value = 123;
printf("The hexadecimal value is: 0x%x", hexadecimal_value);
This will output "The hexadecimal value is: 0x7b" to the console. Now, we will look at the C program implementation of the read and write methods to display hexadecimal values in the terminal.
How to Read Hexadecimal Values in C
We can read hexadecimal input in C using the "%x" format specifier and the scanf() method. This format specifier instructs scanf() to interpret the entered value as a hexadecimal number.
Here is an example program that reads a user-entered hexadecimal value and prints it to the console:
#include <stdio.h>
int main() {
int value_entered;
printf("Please enter a hexadecimal value: ");
scanf("%x", &value_entered);
printf("The decimal value of the hexadecimal you entered is: %d\n", value_entered);
return 0;
}
We first declare an int variable named "value_entered". We then use printf() to prompt the user to enter a hexadecimal value. The input is read as a hexadecimal number using scanf() and the "%x" format specifier, and stored in "value_entered".
Finally, we print the user-entered value using printf(). The decimal equivalent of the hexadecimal value is printed with the "%d" specifier.
When you run the program, the following output will display in the terminal:
Please enter a hexadecimal value: 1a
The decimal value of the hexadecimal you entered is: 26
This demonstrates reading a hexadecimal input from the user and printing its decimal equivalent.
How to Write Hexadecimal Values in C
We can use the printf() function and "%x" format specifier in C to write hexadecimal values. Here is an example that writes a value in hexadecimal format in C:
#include <stdio.h>
int main() {
int decimal_value = 15;
printf("The given decimal value is: %d\n", decimal_value);
printf("The hexadecimal value of the given decimal is: 0x%x\n", decimal_value);
return 0;
}
First, the integer variable "decimal_value" is declared and initialized to 15 in decimal form.
The decimal value of "decimal_value" is printed using printf() and "%d" format specifier.
Then the contents of "decimal_value" are printed to the console again using printf(). This time, we use the "%x" specifier along with the "0x" prefix to indicate the value is in hexadecimal format.
When you execute this program, the console will first display 15 in decimal, then the hexadecimal representation:
The given decimal value is: 15
The hexadecimal value of given decimal value is: 0xf
This shows writing the same value in both decimal and equivalent hexadecimal forms in C.
Hexadecimal Conversion Functions in C
C provides built-in functions for converting between decimal, hexadecimal and other number systems:
strtol()
The strtol() function converts a string to a long integer. We can use it to convert a hexadecimal string to a decimal number:
#include <stdio.h>
#include <stdlib.h>
int main() {
char* hex_str = "1a";
long decimal;
decimal = strtol(hex_str, NULL, 16);
printf("Hexadecimal %s = Decimal %ld", hex_str, decimal);
return 0;
}
Here strtol()
takes the hex string, and 16 as the base to know it‘s a hex input. It returns the decimal integer equivalent.
strtoul()
strtoul() is the same as strtol() but returns an unsigned long integer.
sprintf()
The sprintf() function can format decimal values to hexadecimal strings:
#include <stdio.h>
int main() {
int decimal = 26;
char hex_str[3];
sprintf(hex_str, "%x", decimal);
printf("Decimal %d = Hexadecimal %s", decimal, hex_str);
return 0;
}
The %x
in sprintf()
formats the decimal to a hex string representation.
Why Use Hexadecimal in C?
There are several key reasons hexadecimal numbers are commonly used in C programming:
-
Concise representation of binary: Hex allows expressing binary numbers in fewer digits than binary or decimal. An 8-bit binary number requires 8 digits (00000000) while hex takes just 2 digits.
-
Readable for humans: Hex values are more concise and easier to read & interpret than long streams of 1‘s and 0‘s. This makes debugging and understanding code easier.
-
Compatibility with CPUs: Since CPUs and memory are based on binary, hex numbers have a direct mapping to the underlying hardware. Hex literals are efficient for manipulating bits and bytes.
-
Addresses and pointers: Pointers and memory addresses are commonly represented in hex. It allows precisely specifying locations in memory.
-
Color codes: Hex is useful for specifying colors in graphics and web development, as colors are often represented by 3 or 6-digit hex RGB codes.
So in systems programming and low-level coding, hexadecimal plays a crucial role in bridging between human-readable code and computer-readable binary. The built-in C features for printing and parsing hexadecimal makes working with hex literals efficient.
Hexadecimal Value Manipulation in C
We can directly manipulate and perform arithmetic on hexadecimal integers in C code. Some examples:
Hexadecimal Assignment
int x = 0xA2; // Assign hex value 162 to x
int y = 0xB5; // Assign hex value 181 to y
Hexadecimal Math
int sum = x + y; // 0xA2 + 0xB5 = 0x157 (342 in decimal)
We can add, subtract, multiply & divide hex values normally as integers.
Bitwise Operations
int z = x & y; // Bitwise AND
int s = x | y; // Bitwise OR
int d = x ^ y; // Bitwise XOR
Common bit manipulations like AND, OR, XOR, shifts etc. work on hex integers.
Hexadecimal Output
printf("x = 0x%X", x); // Print x in hex
printf("sum = 0x%04X", sum); // Print hex sum 0x0157 with leading zeros
So hex values can be declared, processed and printed directly in C without needing explicit conversion.
Example: Hexadecimal Counter in C
Here is a practical example of using hexadecimal numbers in C – a program that implements a counter printing values from 00 to FF (255 decimal) in hex:
#include <stdio.h>
int main() {
int i;
int max_count = 255; // FF hex
printf("Hexadecimal Counter:\n");
for(i=0; i <= max_count; i++) {
printf("0x%02X\n", i); // Print hex values with leading 0
}
return 0;
}
When you run this:
Hexadecimal Counter:
0x00
0x01
0x02
...
0XFE
0XFF
It will output all integers from 0 through 255 encoded as two-digit hex numbers. This demonstrates hex manipulation by incrementing i
as a hex value, formatting and printing it.
The leading zeros ensure two digits using the %02X
printf format. This pads any single hex digits with a 0 prefix.
This kind of counter is useful for incrementing through hex memory addresses, color codes, ASCII characters or other hex integer sequences.
Conclusion
We have covered different methods to read, write and manipulate hexadecimal numbers within C programs. Due to the integral role hex plays in computing and systems programming, being able to handle hexademical values effectively is an important skill for any C developer.
The built-in hex support through scanf %x
, printf %X
, strtol() and other functions provide efficient ways to parse, print and convert hexadecimal numbers. With some knowledge of the hex syntax, representing binary data in code becomes simpler.
Understanding hexadecimal conversion will help with debugging C programs, interpreting memory addresses, communicating with hardware devices and other low-level development. So learning to leverage hex where appropriate can make writing, debugging and enhancing C programs an easier process.