Home » C programming language

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.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.