How to save sbyte value in byte variable?

I am programming in C #. I have a sbyte variable. Say it contains -10, which is in binary 11110110. I want to store the binary representation of this value in a byte variable. So when I copy sbyte (-10) to bytes, the byte value will be 245. If I try to use Convert.ToByte (sbyte), it throws an exception that makes sense. I really do not want to convert from one type to another, but rather make a battered copy. How can i do this?

+3
source share
2 answers

Just click:

byte b = (byte) x;

If your code usually works in a trusted context, you want to disable this operation:

byte b = unchecked((byte) x);

, -10 246, 245.

+10

:

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

Source: https://habr.com/ru/post/1749592/


All Articles