tags:

views:

488

answers:

5

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.

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.

Could anyone give me a viable alternative?

Thank you very much for the support.

+1  A: 

I think this might be because you're casting the 255 integer literal to a byte, rather than assigning a byte value. I recommend you try using using Byte.MaxValue instead. Byte.MaxValue has a value of 255.

For example:

buf[i] = byte.MaxValue;

Edit: I was wrong; (byte)255 definitely evaluates to 255; I've just confirmed in VS. There must be something you're doing to cause the change elsewhere in your code.

Randolpho
"The value of this constant is 255 (hexadecimal 0xFF)."
Steven Sudit
I'm aware of that. But he's trying to cast 255, which is an integer literal, to a byte. I think *that* may be causing the problem he keeps seeing. Instead of using the cast, I recommend using Byte.MaxValue, which has the value of 255. I shall edit and clarify.
Randolpho
No, you can cast 255 to byte just fine.
Steven Sudit
Yeah, I fired up VS and tried it; (byte)255 definitely evaluates to 255. There must be something else going on.
Randolpho
@Randolpho: Expanding on Steven's comment, you can cast any integer literal without a suffix to a variable capable of representing it *without a cast*. -1 can be assigned to sbyte, short, int, long. 0xFFFFFFFF can be assigned to uint, long, ulong. 255 can be assigned to any integer type except sbyte.
280Z28
Yeah, yeah, stupid C# compiler is too smart for me. I thought that maybe the cast was causing the problem; clearly I was wrong.
Randolpho
+3  A: 

I think you've misdiagnosed your problem: .NET bytes are 8-bit like everyone else's. 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#.

Steven Sudit
A: 

byte.MaxValue equals 255.

The value of this constant is 255 (hexadecimal 0xFF).

280Z28
A: 

Are you absolutely sure about this C# "limitation", according to MSDN : http://msdn.microsoft.com/en-us/library/5bdb6693%28VS.71%29.aspx

The C# byte is an unsigned 8 bit integer with values that can range between 0 and 255.

LorenVS
A: 

From MDSN

byte:

The byte keyword denotes an integral type that stores values as indicated in the following table.

  • .NET Framework type: System Byte
  • Range: byte 0 to 255
  • Size : Unsigned 8-bit integer
johnc