short i = 25991;
byte[] b = new byte[2];
b[0] = (byte)((0xff00 & i) >> 8);
b[1] = (byte)(0xff & i);我们知道,每个Unicode字符占用2个字节,那么按上边的思路将Unicode字符转成byte也就容易了:
char c = '文'; //一个 Unicode 字符
short i = (short)c;
byte[] b = new byte[2];
b[0] = (byte)((0xff00 & i) >> 8);
b[1] = (byte)(0xff & i);测试发现:short的取值范围为[-32768,32767],将编码大于32767的字符转为short时结果为负数,但不影响转化成byte[]的结果,也可考虑将short转换成ushort。
char c = '文'; //一个 Unicode 字符
[color=Red]ushort[/color] i = ([color=Red]ushort[/color])c;
byte[] b = new byte[2];
b[0] = (byte)((0xff00 & i) >> 8);
b[1] = (byte)(0xff & i);
评论(0)
暂无评论。