- // Created by Ant 2014-4-30
- public static class BytesConverterUtility
- {
- public static byte[] GetBytes(intvalue,intlength,boolisLittleEndian =true)
- {
- if(value <0)
- {
- throw newArgumentException("value不能为负数");
- }
- if(length >4)
- {
- throw newArgumentException("length不能>4");
- }
- varrawBytes = BitConverter.GetBytes(value);
- if(rawBytes.Length < length)
- {
- throw new ApplicationException(
- String.Format("BitConverter.GetBytes返回的字符数{0}小于目标字符数{1}", rawBytes.Length, length));
- }
- varbytes =new byte[length];
- if(BitConverter.IsLittleEndian != isLittleEndian)
- {
- Array.Reverse(rawBytes);
- Array.Copy(rawBytes, rawBytes.Length - length,
- bytes, 0, length);
- }
- else
- {
- Array.Copy(rawBytes, bytes, length);
- }
- return bytes;
- }
- public static intToInt(byte[] bytes,intoffset,intlength,boolisLittleEndian =true)
- {
- if(length ==1)
- {
- return bytes[offset];
- }
- vartempBytes =new byte[length];
- Array.Copy(bytes, offset, tempBytes, 0, length);
- if(!isLittleEndian)
- {
- Array.Reverse(tempBytes);
- }
- switch (length)
- {
- case 2:
- // 特殊处理,转换为无符号int类型,返回时自动转换为Int32
- returnBitConverter.ToUInt16(tempBytes,0);
- case 4:
- // 注意,这里将数据转换为有符号int类型
- returnBitConverter.ToInt32(tempBytes,0);
- default:
- throw newArgumentException("length 长度非标准值");
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2038825.html