Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to form a 64bit number using 2 pointers?

Tags:

c

pointers

Suppose I have two pointers

uint64_t* ptr1;
uint64_t* ptr2;

I have to form a var value such that 6 bytes are taken from ptr1 and 2 bytes from ptr2 and currently ptr1 has consumed its initial 2 bytes and now the remaining bytes left to be processed is 6 bytes.

I wrote something like this

uint64_t value = (uint64_t)((*ptr1) >> 16);\
value = (uint64_t)(value << 16 | (*ptr2 & 0x000000000000ffff));\

Ideally its the mask should be 0xffff000000000000, but it doesn't work.(For processing purposes). How should I proceed and what am I doing wrong here? According to me it should just be

value = (uint64_t)((*ptr1 & ~0x000000000000ffff)  << 16 | (*ptr2 & 0xffff000000000000));

EDIT: ptr1 here points to (uint8_t*)ptr1 +2, i.e 2 bytes after ptr1

like image 507
Hooli Avatar asked Mar 07 '26 21:03

Hooli


1 Answers

First write the mask

#define mask 0xFFFFFFFFFFFF 

Extract 6 bytes out of ptr1 and store them

const uint64_t first_six = *ptr1 & mask;

Extract 2 bytes out of ptr2 and store them

const uint16_t last_two = *ptr2 & 0xFFFFull;

Finally, put them together

uint64_t value = (first_six << 16) | last_two;

In a single expression

uint64_t value = ( (*ptr1 & mask) << 16 ) | (*ptr2 & 0xFFFFull);

I also wanted to know if endianness matters during masking?

Endianness has no importance in this case.

like image 80
edmz Avatar answered Mar 10 '26 11:03

edmz



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!