2019-4-29-C#-从-short-转-byte-方法

title author date CreateTime categories
C# 从 short 转 byte 方法
lindexi
2019-4-29 12:8:39 +0800
2019-01-06 10:39:23 +0800
C#

本文告诉大家多个方法转换 short 和 byte 有简单的也有快的

快速简单的方法

static short ToShort(short byte1, short byte2)
{
    return (byte2 << 8) + byte1;
}

static void FromShort(short number, out byte byte1, out byte byte2)
{
    byte2 = (byte) (number >> 8);
    byte1 = (byte) (number & 255);
}

简单的方法

通过BitConverter 可以将大量的类转换为 byte 包括 short 的方法

short number = 42;
byte[] numberBytes = BitConverter.GetBytes(number);
short converted = BitConverter.ToInt16(numberBytes);

但是为了这么简单的 short 两个 byte 创建一个数组,感觉不是很好

https://stackoverflow.com/q/1442583/6116637

原文地址:https://www.cnblogs.com/lindexi/p/12086661.html