C # Java code migration, conversion without signed short and byte arrays

I am writing a piece of code in Java (I am pretty new to Java) that I previously wrote in C #. Here's the code and example in C #.

ushort number = 0xAABB; // 43707 byte[] data = new byte[2]; EndianBitConverter.Big.CopyBytes(number, data, 0); // value[0] = 170, value[1] = 187 

I use the custom convrter bit in .NET, as it defaults to little endian. In any case, from what I understand about java, if I want to use the same result as byte [], I should expect my values โ€‹โ€‹(170 and 187) to be less by 128 (Byte.MAX_VALUE + 1) , i.e. (42, 59) - because of .net and java having a different range for a type byte. Here is what I wrote in Java to emulate my logic above.

 public class Ushort { private int value = 0; public Ushort(int i) { value = i - (Short.MAX_VALUE + 1); } public int get() { return value; } public byte[] getBytes() { byte[] result = new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; return new byte[]{result[2], result[3]}; } } 

However, when I call the above code with

 new Ushort(0xAABB).getBytes() 

The result is [42, -69] [42, 59]. The last byte is 128 less than it should. I really need some pointers on how to do this correctly, and if my logic is correct. I also need to do the same for uint, ulong, etc., so I need to get it right.

+4
source share
2 answers

Either I donโ€™t understand the reasons for the conversions you are trying to do, or they are mistakenly conceived, which means that I canโ€™t understand if there is an error in their implementation.

The byte type in java is exactly the same as the sbyte type in C #, so you can run all your C # tests with sbyte and make sure everything works correctly before porting to java.

 (byte)0xaa = 170 (sbyte)0xaa = -86 (byte)0xbb = 187 (sbyte)0xbb = -69 

So, in Java, your byte array should be {-86, -69}.

+5
source

I did not test it, but I would do it:

 public class Ushort { private int value = 0; public Ushort(int i) { // Changed if (i > 0xFFFF || i < -(0xFFFF)) throws IllegalArgumentException("integer overflow") value = i; } public int get() { return value; } public byte[] getBytes() { // Changed! (Use & 0xFF) return new byte[]{ (byte) ((value >>> 8) & 0xFF), (byte) (value & 0xFF)}; } } 
+3
source

Source: https://habr.com/ru/post/1383676/


All Articles