D
Dave
Hi all,
I have a 4 byte char array with the binary data for two 16-bit signed
integers in it like this:
Index 3 2 1 0
Data Bh Bl Ah Al
Where Bh is the high byte of signed 16-bit integer B and so on.
I want to create 32-bit integers A and B with the data in the char
array.
I have tried things like (and various other permutations):
A = (data[1] << 8) | (unsigned int)data[0];
B = (data[3] << 8) | (unsigned int)data[2];
and this works except for when say data[1] = 0x00 and data[0] = 0x80.
In this case, Al gets sign extended all the way to the top of A giving
0xffffff80 which is wrong of course.
I read about the arithmetic converions and I believe it is these that
are converting the right operand to signed and causing the sign
extension.
At the moment, I am getting things right like this:
int A;
int B;
char buildA[4], buildB[4], data[4];
// data[] gets filled here
buildA[0] = data[0];
buildA[1] = data[1];
if (data[1] >> 7)
{
buildA[2] = (char)0xff;
buildA[3] = (char)0xff;
}
else
{
buildA[2] = 0x00;
buildA[3] = 0x00;
}
buildB[0] = data[2];
buildB[1] = data[3];
if (data[3] >> 7)
{
buildB[2] = (char)0xff;
buildB[3] = (char)0xff;
}
else
{
buildB[2] = 0x00;
buildB[3] = 0x00;
}
A = *((int*)buildA);
B = *((int*)buildB);
Surely there is a cleaner way?
Many thanks for your time,
Dave
I have a 4 byte char array with the binary data for two 16-bit signed
integers in it like this:
Index 3 2 1 0
Data Bh Bl Ah Al
Where Bh is the high byte of signed 16-bit integer B and so on.
I want to create 32-bit integers A and B with the data in the char
array.
I have tried things like (and various other permutations):
A = (data[1] << 8) | (unsigned int)data[0];
B = (data[3] << 8) | (unsigned int)data[2];
and this works except for when say data[1] = 0x00 and data[0] = 0x80.
In this case, Al gets sign extended all the way to the top of A giving
0xffffff80 which is wrong of course.
I read about the arithmetic converions and I believe it is these that
are converting the right operand to signed and causing the sign
extension.
At the moment, I am getting things right like this:
int A;
int B;
char buildA[4], buildB[4], data[4];
// data[] gets filled here
buildA[0] = data[0];
buildA[1] = data[1];
if (data[1] >> 7)
{
buildA[2] = (char)0xff;
buildA[3] = (char)0xff;
}
else
{
buildA[2] = 0x00;
buildA[3] = 0x00;
}
buildB[0] = data[2];
buildB[1] = data[3];
if (data[3] >> 7)
{
buildB[2] = (char)0xff;
buildB[3] = (char)0xff;
}
else
{
buildB[2] = 0x00;
buildB[3] = 0x00;
}
A = *((int*)buildA);
B = *((int*)buildB);
Surely there is a cleaner way?
Many thanks for your time,
Dave