04-12-2010 08:42 AM
Hello,
I'm having difficulties to convert an signed short int (2byte) into an array of two chars.
My current try is like this:
void ConvertShortIntToByteArray(short int value)
{
unsigned char byteHi = 0x00; // High Byte of result
unsigned char byteLo =0x00; // Low Byte of result
unsigned char C1 = 0x00;
unsigned char C2 = 0x00;
unsigned char C3 = 0x00;
unsigned char C4 = 0x00;
short int tempValue = 0;
C4 = value % 16;
tempValue = value / 16;
C3 = tempValue % 16;
tempValue /= 16;
C2 = tempValue % 16;
tempValue /= 16;
C1 = tempValue % 16;
byteHi = C1 << 4;
byteHi += C2;
byteLo = C3 << 4;
byteLo += C4;
}
It works OK for positive values (for example saying that 240 = 0x00 F0) but negative values don't work here.
Is there a way to convert signed short int values to a two byte array in a more easy way?
I know the correct way could be to go over binary like this:
Assume value = -240:
So abs(-240) = 240 = 00 F0 = 0000 0000 1111 0000
One-Complement:
1111 1111 0000 1111
Add '1' to the One-Complement:
1111 1111 0000 1111
+0000 0000 0000 0001
-------------------
1111 1111 0001 0000
Result = 1111 1111 0001 0000 = FF 10 = -240
But isn't there a more easy way that doesn't have to go over binary to achieve this?
Any help is greatly appreciated.
Thank you and best regards,
Bernd
Solved! Go to Solution.
04-12-2010 08:50 AM
If you want to just let C do its thing:
void ConvertShortIntToByteArray(short int value) { unsigned char byteHi = value >> 8; // High Byte of result unsigned char byteLo = value; // Low Byte of result }
Or perhaps a little more understandably:
void ConvertShortIntToByteArray(short int value) { unsigned char byteHi = (value >> 8) & 0xff; // High Byte of result unsigned char byteLo = value & 0xff; // Low Byte of result }
04-12-2010 08:57 AM
Thank you a lot, Martin.
This solves the problem. Seems as if I thought too much about bits'n'bytes to not see the simple way.
Best regards,
Bernd
04-13-2010 03:47 PM
You can also do this with a union. Unions are powerful things and very useful but use them wisely as they can get confusing.
Define the union something like this:
typedef union { short int si;
unsigned char ch[2];
} si2uchar;
Then use it be declaring a variable of type si2uchar and accessing it as either a short int or 2 element array of unsigned char by using the dotted notations like this:
si2uchar utest;
utest.si = 0x1234;
// utest.uchar[0] is now 0x12 and utest.uchar[1] is 0x34
utest.uchar[0] = 0x55;
utest.uchar[0] = 0xaa;
// utest.si is now 0x55aa