[英]Convert unsigned long to char*, disregard high 0 bytes
I have an unsigned long long variable which I want to write to a binary file. 我有一个无符号的long long变量,我想将其写入二进制文件。 However, I need to neglect all leading bytes which are zero.
但是,我需要忽略所有为零的前导字节。
This means 这意味着
unsigned long long toWrite = 4;
should write 0x04 and not 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x04 to the stream. 应该将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;
}
I was thinking about making cutoffZeroBytes
a function which returns a char*
. 我正在考虑使
cutoffZeroBytes
一个返回char*
的函数。 But if there are zero bytes in the middle (eg 0x03 0x00 0xf1), then I think I couldn't write it to the stream, since 0x00 determines the end of an char
array. 但是,如果中间有零个字节(例如0x03 0x00 0xf1),那么我认为我无法将其写入流,因为0x00确定了
char
数组的结尾。 I'm a little clueless here and need some help. 我在这里有点笨,需要一些帮助。
One way is using write for this aim. 一种方法是将写入用于此目的。 So, just change:
因此,只需更改:
out << cutoffZeroBytes(toWrite);
to: 至:
out.write((char*)&toWrite, sizeof(toWrite));
And if you want to cut this number: 如果要减少此数字:
char* start = (char*)&toWrite;
int pi = sizeof(toWrite);
for (; pi > 0; pi--, start++)
if (*start)
break;
out.write(start, pi);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.