首页 > 解决方案 > 十六进制到浮点数 - 中小字节序 (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;
}

标签: javascript

解决方案


对于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 );


推荐阅读