1

I have been writing a rather low level application in C# that uses a lot of bytes shorts and bit manipulation. One thing I noticed is that C# doesn't like to do bit manipulation and use boolean operators on anything other than ints. This has resulted in 100's of casts all over my code. Errors such as "Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)"

byte b1 = 0x22;
byte b2 = 0x33;
ushort s1 = b1 << 8; // <-- Error Here
ushort s2 = s1 | b2; // <-- And Here

This forces me to use casts everywhere.

byte b1 = 0x22;
byte b2 = 0x33;
ushort s1 = (ushort)(b1 << 8 | b2);

This should at most be a warning. Even if b1 and b2 where of type ushort it is still an error. Even basic arithmetic such as addition gives the same error.

ushort s1 = 0x22;
ushort s2 = s1 + 0x11; // <-- Oh Come On.
ushort s3 = 8;
ushort s4 = (s1 << s3 | s2); // <-- Still an Error.

Is there anyway around this or do I just have to resign myself to the fact that casts are just a part of C# life when it comes to using anything other than integers or just use C++ where this is not a problem.

John ClearZ
  • 952
  • 2
  • 9
  • 16
  • 3
    Or you could just use `int`s. – Gabe Oct 11 '11 at 01:54
  • For whatever reason, the byte datatype has these odd restrictions that the others do not. The conversions are marked explicit, so you have to cast them. – Joe Oct 11 '11 at 01:58
  • Regarding `ushort s2 = s1 + 0x11;`, see http://stackoverflow.com/questions/4343624/integer-summing-blues-short-short-problem/4347752#4347752 – Bradley Grainger Oct 11 '11 at 02:15

2 Answers2

3

If you look at the native code in the debugger, you see that pretty much all of this arithmetic is done as ints anyway. I've come to the conclusion that the best thing to do is reflect this in my code by using ints for locals and casting only when copying the value into my data structure.

phoog
  • 42,068
  • 6
  • 79
  • 117
1

Unfortunately there is no way around this. It is just how the language was designed (and in fact it goes deeper than the language and into the CLR where all bit-wise logic is performed as Int32 data types).

You can either keep doing the casts, create wrapper functions/classes or switch to unsafe/C++ code and do it in there.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151