Copying integer value to character buffer and vice versa in C

In this article, we will learn how to copy an integer value to character buffer and character buffer to integer variable using pointers in C programming language?
Submitted by IncludeHelp, on June 04, 2018

While working on the embedded programming, if you need to assign an integer value to the character buffer and character buffer (that contain integer value in hexadecimal format) to integer value, you can make it possible by using the pointers.

1) Copying Integer to character buffer

 memcpy(buffer, (char*)&ival,sizeof(unsigned int)); 

Here,

  • buffer is a character array
  • ival is an unsigned integer variable, cast type to character pointer (char*) is applied here to copy it into character buffer
  • sizeof(unsigned int) is the number of bytes to be copied

2) Copying character buffer to integer

 ival = *(unsigned int*)(buffer);

Here, buffer is copying to ival by using assignment (=) operator and cast typing to (unsigned int*) - it will read 4 bytes (size of unsigned int) from buffer base index and assignment operator will assign it into ival.

Example to copy integer value to character buffer and vice versa in C

#include <stdio.h>
#include <string.h>

int main(void) 
{	
	unsigned int ival = 12345;
	char buffer[4];
	int i;

	//converting integer value to character buffer
	memcpy(buffer, (char*)&ival,sizeof(unsigned int));
	//value will be in the hexadecimal format
	// so need to print it in hexadecimal format

	//integer value will be copied in the form of bytes 
	printf("Character buffer: ");
	for(i=0; i<sizeof(unsigned int); i++)
		printf("%02X ", buffer[i]);
		
	//converting string formatted value to unsigned int
	ival =0;
	ival = *(unsigned int*)(buffer);

	printf("\nival = %d\n",ival);

	return 0;
}

Output

    Character buffer: 39 30 00 00 
    ival = 12345

Explanation:

Note that, the Hexadecimal value of 12345 is 00003039 in 4 bytes format: {0x00, 0x00, 0x30, 0x39}, after copying to buffer all bytes will be copied to the buffer. Therefore, the value of buffer is "39 30 30 30".

And, after copying it to integer variable the value of ival is again 12345.


Related Tutorials



Comments and Discussions!

Load comments ↻





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