您好我想将一些utf 8个字符的值硬编码为字节。
例如:'$'
,'-'
,'+'
;
对于'$'
,如何计算字节值:
symbol char octal code point binary code point binary utf8
$ U+0024 044 010 0100 00100100
这些列被编码为byte的值是什么?
public class Constants{
public const byte dollar= [value pick from where ?]
public const byte minus= [pick value from where?]
}
我应该寻找上面的哪一列来编码一个字节?是char
列值和字节值之间是否有任何公式?
答案 0 :(得分:1)
您引用的字符不是UTF-8字符。所以它们是单字节字符。 (注意,UTF-8仅对ASCII字符集之外的字符使用2个字节)
由于上述原因,您可以直接投射它们:
public const byte dollar = (byte)'$';
如果您需要以字节为单位的UTF-8字符,则应使用:
public static readonly byte[] trademark = new byte[] { 194, 153 };
或者,更明确,但也表现最差:
public static readonly byte[] trademark = Encoding.UTF8.GetBytes("\u0099");
答案 1 :(得分:1)
对于ASCII字符(0-127范围内的字符),您可以简单地转换它们
public const byte dollar = (byte)'?';
否则:
public const byte dollar = 0x0024;
char
列。删除U+
并添加0x。仅对0x0000-0x007F范围内的字符有效。
请注意,编译代码没有区别:sharplab:
public const byte dollar = (byte)'$';
public const byte dollar2 = 0x0024;
编译为:
.field public static literal uint8 dollar = uint8(36)
.field public static literal uint8 dollar2 = uint8(36)
使用C#7.0,如果你讨厌这个世界而你想混淆你的代码,你可以:
public const byte dollar = 0b00100100;
(他们添加了二进制文字,0b
是前缀)