开发者

How can I store a sbyte value in a byte variable?

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 co开发者_JS百科nvert from one type to the other but rather make bit-wise copy. How can I do that?


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.


Just cast it:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜