使用miscutil的C#和Java大端字节之间的区别 [英] Difference between C# and java big endian bytes using miscutil

查看:245
本文介绍了使用miscutil的C#和Java大端字节之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 miscutil 库与Java和C#之间进行通信使用套接字的应用程序.我试图找出以下代码之间的区别(这是Groovy,但是Java结果是相同的):

I'm using the miscutil library to communicate between and Java and C# application using a socket. I am trying to figure out the difference between the following code (this is Groovy, but the Java result is the same):

import java.io.*

def baos = new ByteArrayOutputStream();
def stream = new DataOutputStream(baos);
stream.writeInt(5000)

baos.toByteArray().each { println it }

/* outputs - 0, 0, 19, -120 */

和C#:

using (var ms = new MemoryStream())
using (EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, ms, Encoding.UTF8))
{
  writer.Write(5000);
  ms.Position = 0;
  foreach (byte bb in ms.ToArray())
  {
    Console.WriteLine(bb);
  }
}

/* outputs - 0, 0, 19, 136 */

如您所见,最后一个字节在Java版本中是-120在C#中是136.

As you can see, the last byte is -120 in the Java version and 136 in C#.

推荐答案

这与以下事实有关:Java(JVM)中的字节已签名,而C#中的字节未签名.它与字节序表示的大小无关.

This has to do with the fact that bytes in Java (the JVM) are signed, and in C# they are not. It has nothing to do with big or little endian representation.

换句话说,Java的字节范围为-128 - 127,而C#字节的范围为0 - 255.

In other words, Java's bytes range from -128 - 127, and C# bytes range from 0 - 255.

因此,当尝试用Java表示高于127的字节时,您溢出并环绕到-120.

Thus, when trying to represent a byte above 127 in Java, you overflow and wrap around to -120.

Java教程:

字节:字节数据类型是8位带符号的二进制补码整数.最小值为-128,最大值为127(含).字节数据类型对于在大数组中节省内存非常有用,因为内存的节省实际上很重要.在限制可以帮助您澄清代码的地方,也可以使用它们来代替int.变量范围有限的事实可以作为文档的一种形式.

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

MSDN :

字节"值类型表示无符号整数,值的范围为0到255.

The Byte value type represents unsigned integers with values ranging from 0 to 255.

这篇关于使用miscutil的C#和Java大端字节之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆