如何使用最大长度为 250MB 的 'cstdint' lib 到 store/pack 位数据序列的固定大小整数?为什么不使用普通的 int?
How do i use the fixed sized integers from 'cstdint' lib to store/pack bit data sequence with maximum length of 250MB? Why to not use normal int?
在我正在做的任务中,我被特别告知:
“C++ 中的整数没有固定大小。要访问具有固定大小的整数,您可以使用库 cstdint。”
我认为建议我使用固定大小的整数来打包位数据(最大 250MB)。我不明白固定大小的 int 在这种情况下有何帮助?我如何使用这些固定大小的整数?我想我应该声明一个结构,但我一点也不确定。
谢谢!
C++ 中的整数不是固定大小的,因为它们可以根据 arch 或其他环境变量(OS、编译器等)具有不同的大小
库cstdint公开了保证大小固定的数据类型,例如类型int8_t保证8位长,你可以使用uint8_t到read/write 你的数据。
读取to/from文件的示例
#include <cstdint>
#include <iostream>
#include <fstream>
int main() {
//writing
uint8_t value = '8';
std::ofstream myoutputfile;
myoutputfile.open("filename");
myoutputfile << value << std::endl;
myoutputfile.close();
//reading
std::ifstream myinputfile;
myinputfile.open("filename");
uint8_t c;
myinputfile >> c;
std::cout << c;
myinputfile.close();
return 0;
}
如果我想写入少量 (<100KB) 的数据,我会这样做:
uint8_t data[5] = { '1', '2', '3', '4', '5' };
//writing
myoutputfile.open("filename");
for (int i = 0; i < 5; i++) {
myoutputfile << data[i];
}
myoutputfile.close();
//reading
myinputfile.open("filename");
for (int i = 0; i < 5; i++) {
myinputfile >> data[i];
std::cout << data[i];
}
myinputfile.close();
在我正在做的任务中,我被特别告知: “C++ 中的整数没有固定大小。要访问具有固定大小的整数,您可以使用库 cstdint。” 我认为建议我使用固定大小的整数来打包位数据(最大 250MB)。我不明白固定大小的 int 在这种情况下有何帮助?我如何使用这些固定大小的整数?我想我应该声明一个结构,但我一点也不确定。 谢谢!
C++ 中的整数不是固定大小的,因为它们可以根据 arch 或其他环境变量(OS、编译器等)具有不同的大小
库cstdint公开了保证大小固定的数据类型,例如类型int8_t保证8位长,你可以使用uint8_t到read/write 你的数据。
读取to/from文件的示例
#include <cstdint>
#include <iostream>
#include <fstream>
int main() {
//writing
uint8_t value = '8';
std::ofstream myoutputfile;
myoutputfile.open("filename");
myoutputfile << value << std::endl;
myoutputfile.close();
//reading
std::ifstream myinputfile;
myinputfile.open("filename");
uint8_t c;
myinputfile >> c;
std::cout << c;
myinputfile.close();
return 0;
}
如果我想写入少量 (<100KB) 的数据,我会这样做:
uint8_t data[5] = { '1', '2', '3', '4', '5' };
//writing
myoutputfile.open("filename");
for (int i = 0; i < 5; i++) {
myoutputfile << data[i];
}
myoutputfile.close();
//reading
myinputfile.open("filename");
for (int i = 0; i < 5; i++) {
myinputfile >> data[i];
std::cout << data[i];
}
myinputfile.close();