How to initialize array elements with hexadecimal values in C?

In this post, we are going to learn how to initialize array elements with the hexadecimal values in C programming language? Here, is a c program, which is using to initialize array elements using hexadecimal values and printing the values in hexadecimal and decimal format.
Submitted by IncludeHelp, on February 07, 2017

Here, we will initialize array elements with one byte Hexadecimal values, remember these points while initialising:

  • Declare an array of unsigned char (it will refer Byte Array or unsigned char array).
  • One Byte value range is 0x00 to 0xFF.

Here is the syntax:

unsigned char array_name[]={value1, value2,...};

Consider the below statement, here I am initialising array with 5 Hexadecimal values...

unsigned char arr[]={0x00,0x05,0xFE,0xFF,0xA5};

Here is the complete program

#include <stdio.h>

int main()
{
	unsigned char arr[]={0x00,0x05,0xFE,0xFF,0xA5};
	int loop;
	
	printf("Array elements are:\n");
	for(loop=0;loop<5;loop++)
		printf("%02X (Decimal: %03d)\n",arr[loop],arr[loop]);
	
	return 0;	
}

Output

Array elements are: 
00 (Decimal: 000) 
05 (Decimal: 005) 
FE (Decimal: 254) 
FF (Decimal: 255) 
A5 (Decimal: 165)

C program to initialize integer array with hexadecimal values

#include <stdio.h>

int main()
{
	//loop counter
	int i;
	
	//declraing integer array and
	//initializing with hexadecimal values
	int arr[]={0x1000, 0x2000, 0x10AF, 0xABCD, 0xF100};
	
	//getting length of the array
	int length = sizeof(arr)/sizeof(arr[0]);
	
	//printing the elements
	for(i=0; i<length; i++)
		printf("arr[%d]: HEX: %04X, DEC: %d\n",i,arr[i],arr[i]);
	
	return 0;
}

Output

arr[0]: HEX: 1000, DEC: 4096
arr[1]: HEX: 2000, DEC: 8192
arr[2]: HEX: 10AF, DEC: 4271
arr[3]: HEX: ABCD, DEC: 43981
arr[4]: HEX: F100, DEC: 61696




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.