如何将unsigned char *转换为unsigned long long int? [英] How to convert unsigned char* to unsigned long long int?

查看:168
本文介绍了如何将unsigned char *转换为unsigned long long int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道一个提供执行此逻辑功能的库,或者可能提供执行此逻辑的方法的库吗?​​

Does anyone know of a library that provides a function that performs this logic or perhaps a method to perform this logic?

我正在尝试转换:

unsigned char test[] = "\x00\x00\x56\x4b\x7c\x8a\xc5\xde";

收件人:

94882212005342 / 0x0000564b7c8ac5de

我知道我可以在 test 中循环遍历每个字节,并利用 sprintf 将每个字节转换为字符串,并使用 strcat将它们连接到缓冲区中,然后通过 strtoull 将缓冲区字符串转换为 unsigned long long .但是,我正在寻找更全面,更简单的东西.有这种方法吗?

I'm aware I could loop over each individual byte in test and utilize sprintf to convert each byte to string and concatenate them into a buffer with strcat and convert the buffer string to unsigned long long via strtoull. However I'm looking for something more comprehensive and simple. Is there such a way?

推荐答案

这只是数学.

unsigned char test[] = "\x00\x00\x56\x4b\x7c\x8a\xc5\xde";
unsigned long long num = 
     (unsigned long long)test[0] << 56 |
     (unsigned long long)test[1] << 48 |
     (unsigned long long)test[2] << 40 |
     (unsigned long long)test[3] << 32 |
     (unsigned long long)test[4] << 24 |
     (unsigned long long)test[5] << 16 |
     (unsigned long long)test[6] <<  8 |
     (unsigned long long)test[7] <<  0;

请记住在转换之前将类型转换为足够宽的文字.

Remember to cast to type wide enough before shifting.

您有8个值:

 { 0x00, 0x00, 0x56, 0x4b, 0x7c, 0x8a, 0xc5, 0xde }

在小数点后是:

 0 0 86 75 124 138 197 222

您想拥有:

 94882212005342

这是:

  94882212005342 = 0*2^56 + 0*2^48 + 86*2^40 + 75*2^32 + 124*2^24 + 138*2^16 + 197*2^8 +  222*2^0

这是一个数学运算.您可以编写ex test [0] * 72057594037927936ull ,但是比 test [0]<<56 .

It's a mathematical operation. You could write ex test[0] * 72057594037927936ull but that's less readable then test[0] << 56.

这篇关于如何将unsigned char *转换为unsigned long long int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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