I want to be able to merge bytes from two unsigned long parameters, taking exactly half of the bytes, the half that starts with the least significant byte of the second param and the rest of the first param.
For example:
x = 0x89ABCDEF12893456
y = 0x76543210ABCDEF19
result_merged = 0x89ABCDEFABCDEF19
First, I need to check whether the system that I work on is little endian or big endian. I already wrote a function that checks that, called is_big_endian().
now I know that char char *c = (char*) &y
will give me the "first"(MSB) or "last"(LSB) (depends whether is big endian or not) byte of y.
Now, I do want to use AND(&) bitwise operator to merge x and y bytes, the question is how can I get only half of the bytes, starting from the LSB.
I mean I can use a "for" loop to go over size_of and then split by 2, but i'm confused how exactly should I do it.
And I also thought about "masking" the bytes, because I already know for sure that the given parameters are "long" which means 16 bits. so maybe I can mask them in the following way?
I want to be able to use it both on 32 and 64 bit systems, which means my code is wrong because i'm using here a fixed size of 64 bit long although I don't know what is the system that the code runs on. I thought about using an array to store all the bits or maybe use shifting?
unsigned long merge_bytes(unsigned long x, unsigned long int y)
{
if (is_big_endian() ==0) {
//little endian system
return (y & 0xFFFFFFFF00000000) | (x & 0xFFFFFFFFFFFF);
}
else
{
return (y & 0x00000000FFFFFFFF) | (x & 0xFFFFFFFFFFFF);
}
}
I have "masked" the right side of the bits if that's a little endian system because the LSB there is the furthest to the left bit. And did the opposite if this is a big endian system.
any help would be appreciated.
Your code is almost correct. You want this:
merged = (y & 0x00000000ffffffff) | (x & 0xffffffff00000000);
There is no need to distinguish between big and little endian. The high bits of a value are the high bits of the value.
The difference is only the representation in memory.
Example: storage of the value 0x12345678
at memory location 0x0000
Little endian:
Address byte
-------------
0000 78
0001 56
0002 34
0003 12
Big endian:
Address byte
-------------
0000 12
0001 34
0002 56
0003 78