将 unsigned long 转换为 char*,忽略高 0 字节

Convert unsigned long to char*, disregard high 0 bytes

我有一个 unsigned long long 变量,我想将其写入二进制文件。但是,我需要忽略所有为零的前导字节。
这意味着

unsigned long long toWrite = 4;

应该将 0x04 而不是 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x04 写入流。

#include <fstream>
int main(){
  std::ofstream out("test.txt", std::ios::binary);
  unsigned long long toWrite = 4;
  out << cutoffZeroBytes(toWrite);
  out.close();
  return 1;
}

我正在考虑使 cutoffZeroBytes 成为 returns 一个 char* 的函数。但是如果中间有零字节(例如 0x03 0x00 0xf1),那么我想我不能将它写入流,因为 0x00 决定了 char 数组的结尾。 我在这里有点无能,需要一些帮助。

一种方法是为此目的使用写入。 所以,只需更改:

out << cutoffZeroBytes(toWrite);

至:

out.write((char*)&toWrite, sizeof(toWrite));

如果你想削减这个数字:

char* start = (char*)&toWrite;
int pi = sizeof(toWrite);
for (; pi > 0; pi--, start++)
    if (*start)
        break;
out.write(start, pi);