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.

Comments and Discussions!

Load comments ↻

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