Tuesday, May 14, 2013

仕事の日々#2: C# byte & Java byte

Although C# could be said a rip off from Java, I would understand why Microsoft made the choice to be different from Sun – because it’s downright confusing when doing low level processing if it’s done the Java way.

Aside from String/string, boolean/bool, endianness etc. beginner coders migrating from C# to Java or vice versa would most definitely make this mistake – C# byte and Java byte

In C#, a byte is an 8-bit unsigned integer (unsigned char for you C/C++ dinosaurs out there), while a byte in Java is an 8-bit signed integer (signed char).

What does that mean?

Well, it meant you’ll screw up your code if you ignore this difference.

C#

for(byte i = 10; --i >= 0; )
   Console.WriteLine("foo");

Java

for(byte i = 10; --i >= 0; )
   System.out.println("foo");

For a more hidden problem:

C#

short i = 0xFF;
byte j = (byte) 0xFF; // (byte) is optional
if(i == j) Console.WriteLine("Yay!");
else Console.WriteLine("Nay!");

Java

short i = 0xFF;
byte j = (byte) 0xFF; // (byte) is mandatory
if(i == j) System.out.println("Yay!");
else System.out.println("Nay!");

If you’re not aware of this problem, your program will most probably compile, probably pass all your tests but randomly fails after live deployment.

Captain Obvious says:
“The samples above behave differently for C# and Java.”

Oh, to make things worse, there’s no “unsigned” keyword in Java. Great. Static casting like a magus.

No comments:

Post a Comment