神奇的指针.libpq二进制数据转换方法相同.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define UINT64CONST(x) ((uint64_t)x)
//打印内存中的值
static void print_hex(const uint8_t *bin_data, int32_t bin_memlen) {
int32_t i = 0;
for (i = 0; i < bin_memlen; ++i) {
fprintf(stdout, "%.2x", bin_data[i]);
}
fprintf(stdout, "\n");
}
//高低字节互换
static uint64_t bswap64(uint64_t x) {
return
((x << 56) & UINT64CONST(0xff00000000000000)) |
((x << 40) & UINT64CONST(0x00ff000000000000)) |
((x << 24) & UINT64CONST(0x0000ff0000000000)) |
((x << 8) & UINT64CONST(0x000000ff00000000)) |
((x >> 8) & UINT64CONST(0x00000000ff000000)) |
((x >> 24) & UINT64CONST(0x0000000000ff0000)) |
((x >> 40) & UINT64CONST(0x000000000000ff00)) |
((x >> 56) & UINT64CONST(0x00000000000000ff));
}
int main(int argc, char** argv) {
double val = 3.1415926, *tmpfloat8_ptr;
int64_t tmp64_val, *tmp64_ptr;
fprintf(stdout, "%.7lf\n", val);
//tmp64_ptr指到val的地址,将double转换为int64_t指针
tmp64_ptr = ((int64_t *)(&val));
print_hex((const uint8_t *)tmp64_ptr, sizeof(int64_t));
//转换为网络字节
tmp64_val = bswap64(*tmp64_ptr);
print_hex((const uint8_t *)(&tmp64_val), sizeof(int64_t));
//从网络字节转回int64指针
*tmp64_ptr = bswap64(tmp64_val);
print_hex((const uint8_t *)tmp64_ptr, sizeof(int64_t));
//int64指针转换为double指针,并打印double指针的值
tmpfloat8_ptr = (double *)tmp64_ptr;
fprintf(stdout, "%.7lf\n", *tmpfloat8_ptr);
return (EXIT_SUCCESS);
}