简体   繁体   English

字节顺序:将Java字节转换为C#

[英]Byte order: converting java bytes to c#

While converting a Java application to C# I came through a strange and very annoying piece of code, which is crucial and works in the original version. 在将Java应用程序转换为C#的过程中,我遇到了一段奇怪且非常烦人的代码,这很关键,并且可以在原始版本中使用。

byte[] buf = new byte[length];
byte[] buf2 = bout.toByteArray();
System.arraycopy(buf2, 0, buf, 0, buf2.length);;
for (int i = (int) offset; i < (int) length; ++i) {
  buf[i] = (byte) 255;
}

The part which is causing a casting error is the set into buf[i] of the byte 255: while in Java it works fine, since java.lang.Byte spans from 0 to 255, .NET System.Byte spans from 0 to 254. Because of this limitation, the output in the C# version of the application is that instead of 255, as expected, the buffer contains a set of 254. 导致转换错误的部分是设置为字节255的buf[i] :在Java中,它工作正常,因为java.lang.Byte范围从0到255,.NET System.Byte范围从0到254。由于存在此限制,因此在C#版本的应用程序中输出的结果是,缓冲区包含一组254,而不是预期的255。

Could anyone give me a viable alternative? 谁能给我一个可行的选择?

Thank you very much for the support. 非常感谢您的支持。

I think you've misdiagnosed your problem: .NET bytes are 8-bit like everyone else's. 我认为您误诊了您的问题:.NET字节像其他所有人一样都是8位的。 A better approach is to try to understand what the Java code is trying to do, then figure out what the cleanest equivalent is in C#. 更好的方法是尝试了解Java代码要执行的操作,然后找出C#中最干净的等效代码。

I think this might be because you're casting the 255 integer literal to a byte, rather than assigning a byte value. 我认为这可能是因为您将255整数文字转换为字节,而不是分配字节值。 I recommend you try using using Byte.MaxValue instead. 我建议您尝试改用Byte.MaxValue Byte.MaxValue has a value of 255. Byte.MaxValue的值为255。

For example: 例如:

buf[i] = byte.MaxValue;

Edit: I was wrong; 编辑:我错了; (byte)255 definitely evaluates to 255; (byte)255肯定为255; I've just confirmed in VS. 我刚刚在VS中确认过。 There must be something you're doing to cause the change elsewhere in your code. 您必须执行某种操作来导致代码中其他地方的更改。

byte.MaxValue equals 255. byte.MaxValue等于255。

The value of this constant is 255 (hexadecimal 0xFF). 该常数的值为255(十六进制0xFF)。

Are you absolutely sure about this C# "limitation", according to MSDN : http://msdn.microsoft.com/en-us/library/5bdb6693(VS.71).aspx 根据MSDN,您对C#“限制”是否绝对确定: http : //msdn.microsoft.com/zh-cn/library/5bdb6693(VS.71).aspx

The C# byte is an unsigned 8 bit integer with values that can range between 0 and 255. C#字节是一个无符号的8位整数,其值的范围可以在0到255之间。

From MDSN MDSN

byte: 字节:

The byte keyword denotes an integral type that stores values as indicated in the following table. byte关键字表示一种整数类型,其存储值,如下表所示。

  • .NET Framework type: System Byte .NET Framework类型:系统字节
  • Range: byte 0 to 255 范围:字节0至255
  • Size : Unsigned 8-bit integer 大小:无符号8位整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM