C# 如何将数字转换为字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/153266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast a number to a byte?
提问by Robert
In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number. e.g long x = 0l;
在 C 和 C++ 中,您可以通过在数字末尾放置一个“l”来告诉编译器一个数字是“long”。例如长 x = 0l;
How can I tell the C# compiler that a number is a byte?
如何告诉 C# 编译器一个数字是一个字节?
采纳答案by Douglas Mayle
According to the C# language specificationthere is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this:
根据C# 语言规范,无法指定字节文字。您必须转换为字节才能获得一个字节。您最好的选择可能是用十六进制指定并向下转换,如下所示:
byte b = (byte) 0x10;
回答by Sklivvz
byte b = (byte) 123;
even though
虽然
byte b = 123;
does the same thing. If you have a variable:
做同样的事情。如果你有一个变量:
int a = 42;
byte b = (byte) a;
回答by casademora
Remember, if you do:
请记住,如果您这样做:
byte b = (byte)300;
it's not going to work the way you expect.
它不会像你期望的那样工作。
回答by aib
MSDN uses implicit conversion. I don't see a byte type suffix, but you might use an explicit cast. I'd just use a 2-digit hexadecimal integer (int) constant.
回答by VVS
No need to tell the compiler. You can assign any valid value to the byte variable and the compiler is just fine with it: there's no suffix for byte.
无需告诉编译器。您可以为 byte 变量分配任何有效值,编译器对它很好:byte 没有后缀。
If you want to store a byte in an object you have to cast:
如果你想在一个对象中存储一个字节,你必须强制转换:
object someValue = (byte) 123;