在C ++中将8个字节的数组转换为带符号的long

在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;