号码字符串与BCD编码互转 c#

/// <summary>
/// 把号码用BCD进行压缩编码。
/// </summary>
/// <param name="Num8BitByte">The num8 bit byte.</param>
/// <returns></returns>
public static byte[] ByteArrayToBCD(byte[] Num8BitByte)//8位的ascii码
{
byte[] Num4bitByte = new byte[8];

Num4bitByte = BitConverter.GetBytes(0xffffffffffffffff);
for (int i = 0; i<Num8BitByte.Length; i++)
{
byte num =Convert.ToByte(Num8BitByte[i] - 0x30);
if (i % 2 == 0)
{
Num4bitByte[i / 2] = Convert.ToByte((Num4bitByte[i / 2] & 0xF0) | num);
}
else
{
Num4bitByte[i / 2] = Convert.ToByte((Num4bitByte[i / 2] &0x0F)| (num << 4));
}

}

return Num4bitByte;
}

/// <summary>
/// BCDs to string.
/// </summary>
/// <param name="bcdNum">The BCD num.</param>
/// <returns></returns>
public static string bcdToString(byte[] bcdNum)
{
string retString="";
byte[] byteChar = new byte[bcdNum.Length];
byteChar = BitConverter.GetBytes(0xffffffffffffffff);
byte tempHigh=0,tempLow=0;
int i = 0;
while (tempHigh != 0x0F && tempLow != 0xF0)
{
tempHigh = Convert.ToByte(bcdNum[i] & 0xF0);//取出高四位;
tempHigh = Convert.ToByte(tempHigh >> 4);
tempLow = Convert.ToByte((bcdNum[i] & 0x0F) << 4);
byteChar[i] = Convert.ToByte(tempLow | tempHigh);
i++;
}
string[] HexString=BitConverter.ToString(byteChar).Trim().Split('-');
foreach (string str in HexString)
{
retString += str.Trim();
}
int LastIndex = retString.IndexOf('F');
return retString = retString.Substring(0, LastIndex);
}




本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/3584157.html,如需转载请自行联系原作者

上一篇:Java入门Day2


下一篇:JSP中文乱码问题详解