我一直在寻找如何将big-endian转换为little-endians.但我找不到任何可以解决我问题的好处.似乎有很多方法可以进行这种转换.无论如何,以下代码在big-endian系统中正常工作.但是我应该如何编写转换函数,以便它也适用于little-endian系统?
这是一个功课,但它只是一个额外的,因为在学校运行大端系统的系统.这只是我很好奇,并希望它也可以在我的家用电脑上工作
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("file.bin", ios::in | ios::binary);
if(!file)
cerr << "Not able to read" << endl;
else
{
cout << "Opened" << endl;
int i_var;
double d_var;
while(!file.eof())
{
file.read( reinterpret_cast<char*>(&i_var) , sizeof(int) );
file.read( reinterpret_cast<char*>(&d_var) , sizeof(double) );
cout << i_var << " " << d_var << endl;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
解决了
所以Big-endian VS Little-endian只是字节的逆序.我写的这个功能似乎无论如何都符合我的目的.我在这里添加它以防万一其他人将来需要它.这只是双倍,但是对于整数,要么使用建议的函数torak,要么可以通过使它仅交换4个字节来修改此代码.
double swap(double d)
{
double a;
unsigned char *dst = (unsigned …Run Code Online (Sandbox Code Playgroud) 基本上我正在阅读一种二进制格式,其中 4 个字节指定要遵循的字符串的大小。所以我想将我从缓冲区读取的 4 个字符转换为 1 个整数。
这是我所拥有的。
int FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
//skip the marker and read next 4 byes
int cursor = cursor + 4; //skip marker and read 4
char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]};
int32_t objSize = tmpbuffer;
return objSize;
}
Run Code Online (Sandbox Code Playgroud)
想法?