1

在我的应用程序中,我必须将 long long 数转换为 8 字节数组。然后我必须将 8 字节数组转换为十六进制字符串。你能帮我解决这个问题吗?我很震惊。

4

2 回答 2

3

进行整数/字节数组转换的一种方法是使用union

union {
    long long l;
    uint8_t b[sizeof(long long)];
} u;

u.l = mylonglong;

然后u.b[]包含可以单独访问的字节。

编辑:请注意@NikolaiRuhe 指出,这种使用union会导致未定义的行为,因此最好memcpy()改用:

uint8_t b[sizeof(long long)];
memcpy(b, &mylonglong, sizeof(b));

如果你想要long long本地字节序的十六进制字符串,那么:

void hexChar(uint8_t b, char *out)
{
    static const char *chars = "0123456789abcdef";
    out[0] = chars[(b >> 4) & 0xf];
    out[1] = chars[b & 0xf];
}

// Make sure outbuf is big enough
void hexChars(const uint8_t *buffer, size_t len, char *outbuf)
{
    for (size_t i = 0; i < len; i++)
    {
        hexChar(buffer[i], outbuf);
        outbuf += 2;
    }
    *outbuf = '\0';
}

并调用它:

char hex[32];
hexChars(u.b, sizeof(u.b), hex);

但是,如果您想要 的十六进制值long long

char hex[32];
sprintf(hex, "%llx", mylonglong);
于 2013-05-31T12:15:59.087 回答
0

那能行吗?

#include <stdio.h>
int main() {
    long long int val = 0x424242;
    char str_val[32];
    snprintf(str_val, sizeof(str_val), "%#llx", val);
    printf("Value : %s\n", str_val);
}
于 2013-05-31T12:17:54.987 回答