java - 如何将c toHex方法转换为java

标签 java android c

有谁知道如何将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/

相关文章:

java - 使用 BigIntegers 和 memoization 调用递归方法时获取 NULL

java - GridBagLayout 中的 anchor 是什么?

java - 开始使用 spring 创建标准 Java 应用程序

java - 具有特定 Product Flavors 依赖性的 android-library

java - 如何计算半径内的最大和最小纬度和经度值?

Python C API : when are we at the end of a Python instruction?

c++ - 如何避免重复使用socket?

java - Spring RestController : reject request with unknown fields

c 段错误 fgets

android - 在android中显示来自后台服务的弹出窗口