Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在用 C# 编程。我有一个 sbyte 变量。假设它拥有 -10,二进制是 11110110。我想将此值的二进制表示形式存储在字节变量中。因此,当我将 sbyte (-10) 复制到字节时,字节值将为 245。如果我尝试使用 Convert.ToByte(sbyte) 它会抛出一个有意义的异常。我真的不想从一种类型转换为另一种类型,而是进行按位复制。我怎样才能做到这一点?
刚投:
byte b = (byte) x;
如果您的代码通常在选中的上下文中运行,则您需要取消选中此操作:
byte b = unchecked((byte) x);
请注意,-10 将变为 246,而不是 245。
只需投射它:
byte b = 130; sbyte a = (sbyte)b; byte c = (byte)a; // will still be 130