My question is about Java.
I need a method that returns an unsigned 16-bit integer converted from two bytes at the specified position in a byte array.
In other words I need the equivalent of the method BitConverter.ToUInt16 of C# for Java that works with Java 7.
In C#
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace CSharp_Shell
{
public static class Program
{
public static void Main()
{
byte[] arr = { 10, 20, 30, 40, 50};
ushort res = BitConverter.ToUInt16(arr, 1);
Console.WriteLine("Value = "+arr[1]);
Console.WriteLine("Result = "+res);
}
}
}
I get the output:
Value = 20
Result = 7700
But when I translate it to Java
import java.util.*;
public class Main
{
public static void main(String[] args)
{
byte[] arr = { 10, 20, 30, 40, 50};
int tmp = toInt16(arr, 1);
System.out.println(("Value = "+arr[1]));
System.out.println(("Result = "+tmp));
}
public static short toInt16(byte[] bytes, int index) //throws Exception
{
return (short)((bytes[index + 1] & 0xFF) | ((bytes[index] & 0xFF) << 0));
//return (short)(
// (0xff & bytes[index]) << 8 |
// (0xff & bytes[index + 1]) << 0
//);
}
}
I am expecting the same output as at C#, but instead of that I get the output:
Value = 20
Result = 30
How can I get the same output with Java?
Java does not provide support for primitive unsigned integers values, but you could utilize the
Integerclass to handle unsigned values. That said, you can adapt a wrapper class that simulates the behavior in C#.As codeflush.dev mentioned, you need to shift the higher-order bits.