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;
}

Output

    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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.