Search code examples
javaandroidcbitwise-operatorsunsigned

Migrate bitwise operators for unsigned types to java (without unsigned types)


I'm migrating an iOS app to Android.

This iOs app uses types like uint32_t. This is an unsigned int 32 which it is not available on Java.

uint32_t range is 0 to 4,294,967,295.

int32_t can hold values from –2,147,483,648 to 2,147,483,647

I have this code in Objective-C:

uint32_t vectorRxV1;
UInt16   xxsDas;

[ ... ]

UInt8 CM_L = (vectorRxV1 & 0xBB000000) >> 24;

And also:

uint32_t vectorTxV0 += ((vectorTxV1<<4) + VectorSelK0) ^ ((vectorTxV1>>5) + VectorSelK1);

And also:

Uint8 sincroRx = (sincroRx & 0xD9);
sincroRx = (sincroRx | 0xA2);

I'm not sure if I use a long instead of uint32_t (or int instead of UInt8, the code above will give different value.

UPDATE

I have these operators: >>, <<, &, ^ and |.

What do you think?


Solution

  • In order to mitigate the absence of unsigned data types, Java introduced the >>> operator for shifting right, which does not sign-extend the value being shifted. This is the only bit operation that would suffer from the fact that the number is interpreted as signed.

    If you replace all uint32_t with int, and replace all >> operations on "unsigned" values with >>>, you will get identical bit patterns in the results of your operations.