javascript - 十六进制到浮点数 - 中小字节序 (CDAB) 和十六进制到 (UINT32 - 大字节序 (ABCD))
问题描述
我有 HEX 格式的数据 444000d6909b7b2c46bd0006,我需要将 HEX 中的 7b2c46bd 转换为 Float - Mid-Little Endian (CDAB)。& 00d6909b (UINT32 - Big Endian (ABCD)) 格式的任何人都可以建议我应该在下面的脚本中进行哪些更改,我为 HEX 到 Float(ABCD) 数据转换创建。提前致谢
// // Convert Hex value to float.
function main(a1) {
var b1 = a1;
var d1= b1.substring(4,12);
var int = parseInt(d1, 16);
if (int > 0 || int < 0) {
var sign = (int >>> 31) ? -1 : 1;
var exp = (int >>> 23 & 0xff) - 127;
var mantissa = ((int & 0x7fffff) + 0x800000).toString(2);
var float32 = 0
for (i = 0; i < mantissa.length; i += 1) { float32 += parseInt(mantissa[i]) ? Math.pow(2, exp) : 0; exp-- }
var c = float32 * sign;
}
else c=0;
return c;
}
解决方案
对于Mid-Little Endian (CDAB),最简单的可能是采用ArrayBuffer方式(使用它的视图)。
首先,通过简单地解析每个组件将您的字符串转换为 Uint8Array:
const hexToUint8 = (str) =>
Uint8Array
.from( str.match( /.{1,2}/g )
.map( (comp) => parseInt( comp, 16 ) )
);
然后交换AB和CD
const [ A, B, C, D ] = hexToUint8( str );
const reordered = new Uint8Array( [ C, D, A, B ] );
最后读为 Float32
const res = new DataView( reordered.buffer ).getFloat32( 0 );
const hexToUint8 = (str) =>
Uint8Array
.from( str.match( /.{1,2}/g )
.map( (comp) => parseInt( comp, 16 ) )
);
const hex = "7b2c46bd";
const [ A, B, C, D ] = hexToUint8( hex );
const reordered = new Uint8Array( [ C, D, A, B ] );
const res = new DataView( reordered.buffer ).getFloat32( 0 );
console.log( res );
对于 ABCD 情况,您也可以走这条路线,而无需交换:
const hexToUint8 = (str) =>
Uint8Array
.from( str.match( /.{1,2}/g )
.map( (comp) => parseInt( comp, 16 ) )
);
const hex = "00d6909b";
const uint8 = hexToUint8( hex );
const res = new DataView( uint8.buffer ).getUint32( 0 );
console.log( res );
甚至尝试Number( "0x" + hex )
。
const hex = "00d6909b";
const res = Number( '0x' + hex );
console.log( res );
推荐阅读
- http - Drupal 7:HTTPS 提交按钮进入 HTTP 页面,然后重定向到 HTTPS
- java - 为JSON创建模型,其中键是android中的值
- java - 如何在 Spring Boot Rest 中正确发布 json 对象
- c# - Unity Android:生成主 dex 列表时出错
- python - 安装 Python 和 R 的要求时,Docker 没有被缓存
- ios - 当托管对象模型更新时,其关系模型不会更新
- django - Queryset Django - 根据重量隔间中的参数日期
- python - AttributeError: dense_prediction_cell_json - 为什么无法加载json文件?
- javascript - 方法 window.top.postMessage 重定向到初始页面
- c# - 如何检查 MethodInfo 是否是特定的接口方法