views:

135

answers:

2

I am programming in C#. I have a sbyte variable. Say it holds -10 which in binary is 11110110. I want to store the binary representation of this value in a byte variable. So when I copy the sbyte (-10) to the byte the bytes value would be 245. If I try to use Convert.ToByte(sbyte) it throws an exception which makes sense. I really don't want to convert from one type to the other but rather make bit-wise copy. How can I do that?

+8  A: 

Just cast:

byte b = (byte) x;

If your code is normally running in a checked context, you'll want to make this operation unchecked:

byte b = unchecked((byte) x);

Note that -10 will become 246, not 245.

Jon Skeet
+2  A: 

Just cast it:

byte b = 130;
sbyte a = (sbyte)b;
byte c = (byte)a; // will still be 130
ho1