ct_pc/SetTools/Tools/Util.cs

99 lines
2.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SetTools
{
class Util
{
//16进制string转byte数组
public static byte[] hexString2bytes(int size, String src)
{
if (size <= 0) return null;
byte[] bs = new byte[size];
int i;
for (i = 0; i < size; i++)
{
bs[i] = Convert.ToByte(src.Substring(i * 2, 2), 16);
}
return bs;
}
//ascii string转byte数组
public static byte[] ascString2bytes(int size, String src)
{
if (size <= 0) return null;
byte[] ss = System.Text.Encoding.ASCII.GetBytes(src);
byte[] bs = new byte[size];
int i = size;
if (i > ss.Length)
{
i = ss.Length;
}
while (i > 0)
{
i--;
bs[i] = ss[i];
}
return bs;
}
//将单个字节数值转string 2位可视16进制字符显示
public static string byteHex2String(Byte value)
{
String t = Convert.ToString(value, 16);
if (t.Length < 2)
{
t = "0" + t;
}
return (t);
}
//16进制byte数组转string
//byte bt = 0x35;
//bt.ToString("x2") = "35"
public static string bytesHex2String(byte[] value)
{
int i, size = value.Length;
StringBuilder sb = new StringBuilder();
for (i = 0; i < size; i++)
{
sb.Append(byteHex2String(value[i]));
}
return (sb.ToString());
}
//byte数组转string
public static string bytes2String(byte[] value)
{
return System.Text.Encoding.GetEncoding("GB18030").GetString(value);
}
//32位数字转string
public static string uint2HexString(UInt32 value) {
return(value.ToString("X2"));
}
//byte转bcd
//bin:0-99
public static byte bin2BCD(byte bin){
byte msb;
if (bin > 99)
{
return (0x99);
}
msb = (byte)(bin / 10);
return (byte)(bin + msb * 6);//bin = msb * 10 + lsb
}
//bcd转byte
public static byte bcd2bin(byte bcd)
{//2位BCD码转二进制
byte msb;//高4位即10位上的值
msb =(byte)(bcd >> 4);
return (byte)(bcd - msb * 6);//bcd = msb*16 + lsb
}
}
}