适用于Java的Bitconverter

按照问题https://stackoverflow.com/questions/1738244/what-is-the-java-equivalent-of-net-bitconverter中提供的建议,我已经开始为Java实现我自己的bitconverter但是没有得到相同的结果。

有人可以指导我可能做错了吗?

public static byte[] GetBytes(Integer value) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream stream = new DataOutputStream(byteStream); try { stream.writeInt(value); } catch (IOException e) { return new byte[4]; } return byteStream.toByteArray(); } byte[] result = BitConverter.GetBytes(1234); //JAVA: [0, 0, 4, -46] byte[] result = BitConverter.GetBytes(1234); //C#: [210, 4, 0, 0] 

这只是字节序(-46和210是因为Java的签名字节,但这只是一个UI事物)。 要么反转数组内容,要么使用shift操作来编写int。

注意:.NET发出的字节顺序取决于平台。 我建议在两种情况下使用KNOWN ENDIANNESS; 最有可能的方法是使用两者的轮class操作。 或者更好的想法:只使用预先封装的,独立于平台的序列化格式(例如:协议缓冲区,它对Java和.NET / C#都有很好的支持)。

例如; 如果我正在将一个int value写入byte[] buffer (从offset开始),我可能会使用:

 buffer[offset++] = (byte)value; buffer[offset++] = (byte)(value>>8); buffer[offset++] = (byte)(value>>16); buffer[offset++] = (byte)(value>>24); 

这是保证little-endian,类似的代码应该适用于任何框架。

C# BitConverter将使用底层架构的字节序。 在大多数环境中,它将是little-endian(就像你的情况一样)。 然而,Java的DataOutputStream总是以big-endian(“便携式方式”)编写。 如果要匹配行为,则需要检查机器的字节顺序并进行相应的编写。

此外,java中的字节是有符号的,因此输出只是一个装饰差异。 位表示是相同的,因此您不必担心这一点。

要检查计算机的字节顺序,请使用java.nio.ByteOrder.nativeOrder()方法。 然后使用java.nio.ByteBuffer ,您可以在其中指定字节order()并写入数据。

然后,您可以像这样实现您的方法:

 public static byte[] GetBytes(int value) { ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()); buffer.putInt(value); return buffer.array(); } 

基于Jeff的答案,您可以使用单个ByteBuffer来转换intbyte[] 。 下面是代码,您可以将其放入要转换为Little Endian的类中:

 ByteBuffer _intShifter = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE) .order(ByteOrder.LITTLE_ENDIAN); public byte[] intToByte(int value) { _intShifter.clear(); _intShifter.putInt(value); return _intShifter.array(); } public int byteToInt(byte[] data) { _intShifter.clear(); _intShifter.put(data, 0, Integer.SIZE / Byte.SIZE); _intShifter.flip(); return _intShifter.getInt(); } 

如果有任何身体需要..C#到JAVA BitConverter.ToInt32

  public static int toInt32_2(byte[] bytes, int index) { int a = (int)((int)(0xff & bytes[index]) << 32 | (int)(0xff & bytes[index + 1]) << 40 | (int)(0xff & bytes[index + 2]) << 48 | (int)(0xff & bytes[index + 3]) << 56); // int a = (int)((int)(0xff & bytes[index]) << 56 | (int)(0xff & bytes[index + 1]) << 48 | (int)(0xff & bytes[index + 2]) << 40 | (int)(0xff & bytes[index + 3]) << 32); //Array.Resize; return a; } 

也是Int16

  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 //); } 

BitConverter.getBytes

 public static byte[] GetBytesU16(long value) { ByteBuffer buffer = ByteBuffer.allocate(8).order(ByteOrder.nativeOrder()); buffer.putLong(value); return buffer.array(); }