Home » Programming Tips & Tricks » C - Tips & Tricks

C - Fastest way to copy two bytes integer number (short int) into byte buffer

By: IncludeHelp, on 21 JAN 2017

Use memcpy() to copy fixed number of bytes into buffer, by using this function we can easily copy (convert) a short int value into Byte buffer.

Let's consider the following statement

memcpy(buffer,(unsigned char*)&value,2);

Here, buffer is a unsigned char array, value is a short type variable and sizeof(short) is the total number of bytes to be copied.

#include <stdio.h>
#include <string.h>
int main()
	short value=4567;
	unsigned char buffer[2];
	memcpy(buffer,(unsigned char*)&(value),sizeof(short));
	//printing two bytes of buffer in HEX
	printf("%02X %02X\n",buffer[0],buffer[1]);
	return 0;


    D7 11

Here is the program

D7, 11 are the two bytes of byte (character) array buffer, Hexadecimal value of 4567 is = 11D7. buffer store D7, 11 because most of the computer system architecture support "little-endian" storage where least significant byte (D7) will be stored first.

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.