Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read two bytes at once from a byte array in C

Tags:

arrays

c

memory

Let's say I have the following array of bytes:

uint8_t barr[4] = {0xCE, 0xCE, 0xCE, 0xCE};

Given an index n, I want to be able to read two bytes:

uint16_t d16 = barr[0];

And have d16 be equal to

0xCECE

Perhaps there is a function in the standard library that can perform such task?

like image 711
Jan Parzydło Avatar asked Jun 26 '26 09:06

Jan Parzydło


1 Answers

A piece of cake:

memcpy(&d16, barr + n, sizeof(d16));

Don't try to convert pointers or use unions. Those either are undefined behaviors, or may trip trap representations. memcpy() is the "canonical" solution (as the C++ boost library does).

like image 178
iBug Avatar answered Jun 28 '26 23:06

iBug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!