c++long到char数组(8字节)到long

如何将 a 更改longchar8 字节的数组以及如何将char8 字节的数组更改为long

#include <iostream>
using namespace std;
int main () {
    long num=33;
    char* z;
    z = new char[8];
    z =  reinterpret_cast<char *>(&num); // long to char array
    long r;
    r = reinterpret_cast<long>(&z); // char array to long
    cout << r << "n";  // why is the output not 33
    printf("%x ", z[0]); //print the 8 Byte char array
    printf("%x ", z[1]);
    printf("%x ", z[2]);
    printf("%x ", z[3]);
    printf("%x ", z[4]);
    printf("%x ", z[5]);
    printf("%x ", z[6]);
    printf("%x ", z[7]);
    return 0;
}

为什么输出r不是 33?

回答

C++20 后:使用 std::bit_cast

C++20 之前:使用 std::memcpy

long to_long(char const (&arr)[sizeof(long)])
{
   long res;
   memcpy(&res, arr, sizeof(res));
   return res;
}


以上是c++long到char数组(8字节)到long的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>