double 类型对字节进行高低位变换(本机字节转换为网络字节)

神奇的指针.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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kmblack1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值