Reputation: 13
i am trying to convert a c++ software in java, however the bit operations don't produce the same results. overview of what i am doing: there's an ascii file with data entries, 2 bytes long, unsigned (0-65535). Now i want to convert the two-byte unsigned int in two one-byte unsigned short ints.
C++ code:
signed char * pINT8;
signed char ACCBuf[3];
UInt16 tempBuf[128];
tempBuf[0] = Convert::ToUInt16(line);
pINT8 = (signed char *)&tempBuf[0];
ACCBuf[0] = *pINT8;
pINT8++;
ACCBuf[1] = *pINT8;
Java code:
int[] ACCBuf = new int[6];
int[] tempBuf = new int[128];
tempBuf[0] = Integer.parseInt(line);
ACCBuf[0] = tempBuf[0] >> 8;
ACCBuf[1] = 0x00FF & tempBuf[0];
this two codes produce different results. any idea why?
Upvotes: 1
Views: 247
Reputation: 74028
This might depend on the endianess of the system. The C++ code has the lower byte in ACCBUF[0]
, if it is a little endian system. The Java code has the upper byte in ACCBUF[0]
, no matter what hardware.
If you want to get the same result in Java, you must swap the high and low byte
ACCBuf[0] = 0x00FF & tempBuf[0];
ACCBuf[1] = tempBuf[0] >> 8;
now you will have the same bits in either Java or C++.
Another difference between the two code snippets are the types used. You have 32 bit ints in the Java code and 16 bit unsigned ints respectively 8 bit chars in C++. This isn't relevant here, but must be kept in mind, when comparing different code snippets.
Upvotes: 1