JavaScript浮点数与4字节十六进制之间互相转换

function float2hex(floatNumber) {

	// 创建一个 4 字节的 ArrayBuffer
	const buffer = new ArrayBuffer(4);

	// 使用 DataView 来操作 ArrayBuffer
	const dataView = new DataView(buffer);

	// 将浮点数写入到 DataView 中
	dataView.setFloat32(0, floatNumber, false); // 第二个参数是偏移量,false 表示使用大端字节序

	// 从 DataView 中读取十六进制表示
	const hexString = dataView.getUint32(0, false).toString(16).toUpperCase();
	
	// 高低位转换
	const byteArray = [];
	for (let i = 0; i < hexString.length; i += 2) {
		byteArray.unshift(hexString.substr(i, 2));
	}
	return byteArray.join('');
}

console.log("浮点数 1234.56 的十六进制表示为:", float2hex(1234.56));
console.log("浮点数 -1234.56 的十六进制表示为:", float2hex(-1234.56));
console.log("浮点数 0.0 的十六进制表示为:", float2hex(0.0));
console.log("浮点数 -0.0 的十六进制表示为:", float2hex(-0.0));
console.log("浮点数 1.0 的十六进制表示为:", float2hex(1.0));
console.log("浮点数 -1.0 的十六进制表示为:", float2hex(-1.0));
console.log("浮点数 1 的十六进制表示为:", float2hex(1));
console.log("浮点数 50000.99 的十六进制表示为:", float2hex(50000.99));
console.log("浮点数 -50000.99 的十六进制表示为:", float2hex(-50000.99));


function hex2float(hexString, precision) {
	precision = parseInt(precision)
	if (isNaN(precision) || precision < 0) {
		precision = 2
	}
	
	// 高低位转换
	const byteArray = [];
	for (let i = 0; i < hexString.length; i += 2) {
		byteArray.unshift(hexString.substr(i, 2));
	}
	
	// 创建一个包含十六进制数的 ArrayBuffer
	const hexValue = '0x' + byteArray.join('');
	const buffer = new ArrayBuffer(4);
	const dataView = new DataView(buffer);
	dataView.setUint32(0, hexValue, false);

	// 从 DataView 中读取浮点数
	const floatValue = dataView.getFloat32(0, false);
	return floatValue.toFixed(precision);
}
console.log('EC519A44转浮点数结果:', hex2float('EC519A44'));	// 输出1234.56
console.log('EC519A44转浮点数结果:', hex2float('EC519A44', 2));	// 输出1234.56
console.log('EC519AC4转浮点数结果:', hex2float('EC519AC4', null));	// 输出1234.56
console.log('00000000转浮点数结果:', hex2float('00000000', null));	// 输出0
console.log('00000080转浮点数结果:', hex2float('00000080', null));	// 输出0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值