1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class Conversion
{
// String to BCD
public static byte[] str2Bcd(String asc)
{
int len = asc.Length;
int mod = len % 2;
if (mod != 0)
{
asc = "0" + asc;
len = asc.Length;
}
byte[] abt = new byte[len];
if (len >= 2)
len = len / 2;
byte[] bbt = new byte[len];
abt = System.Text.Encoding.ASCII.GetBytes(asc);
int j, k;
for (int p = 0; p < asc.Length / 2; p++)
{
if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9'))
j = abt[2 * p] - '0';
else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z'))
j = abt[2 * p] - 'a' + 0x0a;
else
j = abt[2 * p] - 'A' + 0x0a;
if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9'))
k = abt[2 * p + 1] - '0';
else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z'))
k = abt[2 * p + 1] - 'a' + 0x0a;
else
k = abt[2 * p + 1] - 'A' + 0x0a;
int a = (j << 4) + k;
byte b = (byte)a;
bbt[p] = b;
}
return bbt;
}
// BCD To String
public static string bcd2Str(byte[] bytes)
{
StringBuilder temp=new StringBuilder(bytes.Length*2);
for (int i = 0; i < bytes.Length; i++)//<P>
{
temp.Append((byte)((bytes[ i ]& 0xf0)>>4));
temp.Append((byte)(bytes[ i ]& 0x0f));
}
return temp.ToString().Substring(0,1).Equals("0")? temp.ToString().Substring(1): temp.ToString();
}
} |
Partager