有谁知道如何将blow代码 fragment 转换为java代码? 谢谢。
void
rawdata_to_hex (const unsigned char *rawdata, char *hex_str, int n_bytes)
{
static const char hex[] = "0123456789abcdef";
int i;
for (i = 0; i < n_bytes; i++) {
unsigned int val = *rawdata++;
*hex_str++ = hex[val >> 4];
*hex_str++ = hex[val & 0xf];
}
*hex_str = '\0';
}
我正在使用下面的代码,但看起来不正确。
public static String toHex(byte[] buf) {
if (buf == null) return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789abcdef";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
我的问题是如何隐藏它?有人可以帮忙吗?
最佳答案
使用下面的方法对我有用
/**
* Convert byte to Hexadecimal
*
* @param bytes
* @return
*/
private static String toHex(byte[] bytes) throws NoSuchAlgorithmException {
BigInteger bi = new BigInteger(1, bytes);
String hex = bi.toString(16);
int paddingLength = (bytes.length * 2) - hex.length();
if (paddingLength > 0) {
return String.format("%0" + paddingLength + "d", 0) + hex;
} else {
return hex;
}
}
或者其他方式
public static String toHex(byte[] bytes) {
StringBuffer buff = new StringBuffer();
for (byte b : bytes) {
buff.append(String.format("%02X", b));
}
return buff.toString();
}
关于java - 如何将c toHex方法转换为java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35451257/