简体   繁体   中英

how to do big endian to little endian byte swap in Java

My data is stored as an int in java. <32bit signed>, which represents an unsigned 16bit value that is always positive.

Big Endian decimal 253 stored as 16bit unsigned hex character 0x00FD is transmitted serially to
Little Endian ARM running Android which shows up as 64768 Decimal which is hex 0xFD00 SO I need to Swap Bytes.

Problem is App is in JAVA that uses mainly signed data types

java byte defined as signed 8 bit java integer defined as signed 32 bit

1   private void UI_Update_RunVars() {byte msb_byte1, lsb_byte2; int Swappedbytes;
2        String ONText;
3        msb_byte1 = (byte) mONTimeCount;
4        lsb_byte2 = (byte) (mONTimeCount>>8);
5        Swappedbytes = ((msb_byte1<<8) + lsb_byte2);
6        ONText = Convert2Time(Swappedbytes);
7        mTextON_Count.setText(ONText);  
8   } 

so my example above, I send 0x00FD for decimal 253 big endian, and it arrives as 0xFD00 on litte endian I call method UI_Update_RunVars(); where mONTimeCount = 0xFD00 I need to swap the bytes to display a decimal number on screen 253 is "4 Minutes, 13 Seconds" in the debugger:

line 3 executes as msb_byte1 = 0x00; line 4 executes as lsb_byte2 = 0xFD; line 5 is where error happens line 5 shows up in debugger as -3 which is correct math but not correct answer line 5 -3 of signed 32 bit integer show up as hex 0xFFFF_FFFD and I want 0x00FD

how do I do unsigned math and string operations when the data type is signed.

my application is simple, take UNSIGNED 16 bit number and convert this to time in the form of hours minutes seconds

so the above code actually works for any hex number as long as the msb is not set,

for instance any number 0x7F or below works, but any number 0x80 or more fails as the msb is the sign bit.

Using bytes actually makes it more complicated. You can do all manipulations with integers. Let v be the value to convert:

int swapped = ((v >> 8) & 0xff) | ((v & 0xff) << 8);

Firstly I thought Integer.reverseBytes should resolve the problem, but the actual problem with the shared code is that, we are reducing the integer to byte, which will make it negative anyways. Instead we can keep the calculations in Integer only.

The extraction of byte level information can be done by bit level operations.

This should work:

int mONTimeCount = 0x00FD;
int msb_byte1, lsb_byte2; int Swappedbytes;
String ONText;
msb_byte1 = mONTimeCount & 0x000000FF;
lsb_byte2 = (mONTimeCount >> 8) & 0x000000FF;
Swappedbytes = ((msb_byte1<<8) | lsb_byte2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM