将C字节数组转换为long long [英] Converting a C byte array to a long long

查看:438
本文介绍了将C字节数组转换为long long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个8字节的数组,其中包含以下数据:

I have an 8-byte array in my application with this data:

00000133339e36a2

此数据表示一个长值(在写入数据的平台上,在Mac上将是一个长时长),其值是

This data represents a long (on the platform the data was written in, on a Mac this would be a long long) with the value of

1319420966562

在实际应用中,这是一组半随机数据,因此数量始终会有所不同.因此,我需要将字节数组转换为可打印的long long.

In the actual application this is a semi-randomized set of data, so the number will always be different. Therefore, I need to convert the byte array into a printable long long.

我尝试将数据直接转换成很长一段时间,但是我想出了

I've tried casting the data directly into a long long, but I came up with

1305392

我应该一直在看上面的数字.

where I should have been seeing the above number.

对于那些比我有更多C字节处理经验的人,我该如何正确地将字节数组转换为long long?

For those of you with more experience in C byte manipulation than I do, how would I correctly convert a byte array to a long long?

奇怪的是,所有解决方案都输出相同的数字:866006690.这是数据的最后四个字节的十进制等效项.

Strangely, all of your solutions keep outputting the same number: 866006690. That is the decimal equivalent of the last four bytes of the data.

推荐答案

union le_long_long_array_u
{
  uint8_t byte[8];
  uint64_t longlong;
} le_long_long_array;

为阵列复制(或仅使用)le_long_long_array.byte[]; 回读le_long_long_array.longlong

Copy (or just use) le_long_long_array.byte[] for the array; read back le_long_long_array.longlong

例如:

fill_array(&le_long_long_array.byte[0]);
return le_long_long_array.longlong;

更多示例:

#include <stdint.h>
#include <stdio.h>

union le_long_long_array_u
{
  uint8_t byte[8];
  uint64_t longlong;
} le_long_long_array;

static uint8_t hex2int (char c)
{
    return (c >= '0' && c <= '9') 
            ? (uint8_t )(c  - '0')
            : ((c >= 'a' && c <= 'f') 
                ? (uint8_t )(c  - 'a')
                : ((c >= 'A' && c <= 'F') 
                    ? (uint8_t )(c  - 'A')
                    : 0));
}

int main (int argc, char **argv)
{
    if (argc == 2)
    {
        int i;
        for (i = 0; i <= 7; i++)
        {
            char *str = argv[1];

            if (str[2*i] == '\0' || str[2*i+1] == '\0')
            {
                printf("Got short string.\n");
                return 1;
            }

            le_long_long_array.byte[i] = (hex2int(str[2*i]) << 4) + hex2int(str[2*i+1]);
        }
        printf("Got %lld\n", le_long_long_array.longlong);
    }
    else
    {
        printf("Got %d args wanted 1.\n", argc - 1);
        return 1;
    }
    return 0;
}

产生:

e e$ gcc -c un.c
e e$ gcc -o un un.o
e e$ ./un 0100000000000000
Got 1
e e$ ./un 0101000000000000
Got 257
e e$ ./un a23639333301000000
Got 1319414347266
e e$ 

就像您期望的小字节序数据一样.

as you would expect for little endian data.

这篇关于将C字节数组转换为long long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆