在C ++中将8个字节的数组转换为带符号的long [英] Convert array of 8 bytes to signed long in C++

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

问题描述

我有一个8字节的数组,我试图用C ++将其转换为带符号的long,似乎无法弄清楚.据我所知,长整数只有4个字节,有人可以提供一些信息吗?是32位还是64位无关紧要?

I have an array of 8 bytes and I'm trying to convert it to a signed long in C++, and can't seem to figure it out. From what I could tell long ints are only 4 bytes, can anybody provide some information on this? Is it going to matter if it is 32 or 64 bit?

推荐答案

您可能应该使用保证长度为8个字节的int64_t.

You probably should use a int64_t which is guaranteeed to be 8 bytes long.

您没有说明数据在数组中的表示方式(字节序),但您可能会使用reinterpret_cast<>甚至更好的方法:使用移位操作来构建"整数.

You don't state how your data is represented (its endianness) into your array but you might use reinterpret_cast<> or even better: use shift operations to "build" your integer.

类似的东西:

unsigned char array[8] = { /* Some values here */ };
uint64_t value = 
  static_cast<uint64_t>(array[0]) |
  static_cast<uint64_t>(array[1]) << 8 |
  static_cast<uint64_t>(array[2]) << 16 |
  static_cast<uint64_t>(array[3]) << 24 |
  static_cast<uint64_t>(array[4]) << 32 |
  static_cast<uint64_t>(array[5]) << 40 |
  static_cast<uint64_t>(array[6]) << 48 |
  static_cast<uint64_t>(array[7]) << 56;

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

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