转换字节顺序
程序员文章站
2024-01-27 15:52:16
...
从PostgreSQL传来的二进制数据是网络字节顺序的,即高位先到,低位后到.
使用时转换成本机字节顺序, 才能万无一失.
使用时转换成本机字节顺序, 才能万无一失.
//将网络字节序的字节数据,转换成本机字节顺序的: long long netToHost_Int8(byte * bytes, int len = 8) { unsigned long long llv = 0; for (int i = 0; i < len; i++){ llv <<= 8; llv |= bytes[i]; } return llv; } double netToHost_Double(char * chars) { unsigned long long llv = netToHost_Int8((byte*)chars); return *(double*)&llv; } int netToHost_Int4(char * chars) { return (int)netToHost_Int8((byte*)chars, 4); } short netToHost_Int2(char * chars) { return (short)netToHost_Int8((byte*)chars, 2); }