C#、Java有关16进制字符串和字节数组之间的转换
C#
Code
/**//// <summary>
/// 16进制字符串转字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] Hex2Bytes(string hex)
{
byte[] result = new byte[hex.Length / 2];
for (int i = 0; i < result.Length; i++)
result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
return result;
}
/**//// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string BytesToHex(byte[] bytes)
{
StringBuilder result = new StringBuilder();
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
result.Append(bytes[i].ToString("X2"));
}
}
return result.ToString();
}
/**//// <summary>
/// 16进制字符串转字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] Hex2Bytes(string hex)
{
byte[] result = new byte[hex.Length / 2];
for (int i = 0; i < result.Length; i++)
result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
return result;
}
/**//// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string BytesToHex(byte[] bytes)
{
StringBuilder result = new StringBuilder();
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
result.Append(bytes[i].ToString("X2"));
}
}
return result.ToString();
}
Java
Code
private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/** *//**
* 将字节数组转换为16进制字符串
* @param bcd
* @return
*/
public static final String bytesToHex(byte[] bcd) {
StringBuffer s = new StringBuffer(bcd.length * 2);
for (int i = 0; i < bcd.length; i++) {
s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
s.append(bcdLookup[bcd[i] & 0x0f]);
}
return s.toString();
}
/** *//**
* 将16进制字符串转换为字节数组
* @param s
* @return
*/
public static final byte[] hexToBytes(String s) {
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
16);
}
return bytes;
}
private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/** *//**
* 将字节数组转换为16进制字符串
* @param bcd
* @return
*/
public static final String bytesToHex(byte[] bcd) {
StringBuffer s = new StringBuffer(bcd.length * 2);
for (int i = 0; i < bcd.length; i++) {
s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
s.append(bcdLookup[bcd[i] & 0x0f]);
}
return s.toString();
}
/** *//**
* 将16进制字符串转换为字节数组
* @param s
* @return
*/
public static final byte[] hexToBytes(String s) {
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
16);
}
return bytes;
}