Reputation: 3
I have a function that allows me to separate a INT value in 2 Bytes
(e.g: INT "123123" results in E0F3; highByte= 0xF3
and lowByte=0xE0
)
using this:
void int2bytes(unsigned char dest[2],int val){
int hByte=0;
int lByte=0;
hByte=val&0XFF;
lByte=val>>8;
dest[0]= (char)hByte;
dest[1]= (char)lByte;
}
my question is:
How do I convert(unify) those 2 bytes to one INT equals to "123123"?
Upvotes: 0
Views: 293
Reputation: 7610
Try
(dest[1] << 8) & dest[0]
IMHO the hByte and lByte is swapped... And what is more 123123 is not a two byte value. Int is signed, so on two bytes the max value is 32767, but int
(usually) is 4 bytes.
I might suggest to use a union
in this case, because you can spare all the arithmetics and you do not need to use explicit conversion at all.
An example code to use union:
#include <iostream>
using std::cout;
using std::hex;
using std::dec;
using std::endl;
int main() {
union int2bytes {
unsigned char byte[sizeof(int)];
int val;
};
int2bytes i;
// Convert int to byte
i.val = 123123;
cout << i.val << " : " << hex << i.val << dec << endl;
for (int j = 0; j < sizeof(int); ++j)
cout << "Byte#" << j << " : " << hex << (int)i.byte[j] << dec << endl;
// Convert byte to int
i.byte[1]--;
cout << i.val << " : " << hex << i.val << dec << endl;
}
The output:
123123 : 1e0f3
Byte#0 : f3
Byte#1 : e0
Byte#2 : 1
Byte#3 : 0
122867 : 1dff3
Union can be improved a little bit
union int2bytes {
unsigned char byte[sizeof(int)];
int val;
int2bytes (const int2bytes& i = 0) : val(i.val) {};
int2bytes (int i) : val(i) {};
};
Now these work
int2bytes i = 123123;
int2bytes j; // j.val == 0
int2bytes k = i;
j = i;
Upvotes: 0
Reputation: 612894
To perform the reverse of your function int2bytes
you simply do this:
int val = (lByte << 8) | hByte;
Although, I think you have the names of your variables back-to-front. I'd call val&0xff
the low byte, and val >> 8
the high byte.
You are also mistaken in supposing that you can fit 123123
into 2 bytes. Remember that 2^16 is 65536
.
I have a function that allows me to separate a int value into 2 bytes (e.g: int "123123" results in E0F3; highByte= 0xF3 and lowByte=0xE0)
Well, E0F3 represented in decimal is equal to 57587. Which is the value you report in the comment you made to my answer.
Now, 123123
represented in hexadecimal is 0x1E0F3
and you need at least three bytes to store that value.
Upvotes: 3