如何将unsigned char数组转换为unsigned long long? [英] how do i convert an unsigned char array into an unsigned long long?

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

问题描述

假设我有8个unsigned char,我想转换为unsigned long long。



例如,如果所有的char都等于0xFF, unsigned long long将等于0xFFFFFFFFFFFFFFFF。



用C或C ++做最有效的方法是什么?

 无符号字符缓冲区

8] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
unsigned long long l = 0;
for(int i = 0; i <8; ++ i){
l = 1 | ((unsigned long long)buffer [i] <<(8 * i));
}

我相信这可以免受字节序。


let's say that i have 8 unsigned char, that i want to convert to an unsigned long long.

for example, if all char are equals to 0xFF, the unsigned long long would be equal to 0xFFFFFFFFFFFFFFFF.

what's the most efficient way to do that with C or C++?

解决方案

Instead of memcpy, you can directly assign the bits

  unsigned char buffer[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
  unsigned long long l = 0;
  for (int i = 0; i < 8; ++i) {
    l = l | ((unsigned long long)buffer[i] << (8 * i));
  }

I believe this is immune to endianness.

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

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