猿问

java等效于php“fnum”解包函数,将十六进制转换为java中的浮点IEEE 754

我在 PHP 中有这个功能:


function hex2float($strHex) {

   $array = unpack("fnum", pack("H*", $strHex));

   return $array['num'];

}

我怎么能用java写呢?


四季花海
浏览 139回答 1
1回答

慕雪6442864

我想以这种方式转换此功能:private Float hex2float(String hexStr) {&nbsp; &nbsp; Float result = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; byte[] decodes = Hex.decodeHex(hexStr.toCharArray());&nbsp; &nbsp; &nbsp; &nbsp; result = getFloat(decodes, 0);&nbsp; &nbsp; } catch (DecoderException e) {&nbsp; &nbsp; &nbsp; &nbsp; // log error&nbsp; &nbsp; }&nbsp; &nbsp; return result;}private float getFloat(byte[] b, int index) {&nbsp; &nbsp; int l;&nbsp; &nbsp; l = b[index + 0];&nbsp; &nbsp; l &= 0xff;&nbsp; &nbsp; l |= ((long) b[index + 1] << 8);&nbsp; &nbsp; l &= 0xffff;&nbsp; &nbsp; l |= ((long) b[index + 2] << 16);&nbsp; &nbsp; l &= 0xffffff;&nbsp; &nbsp; l |= ((long) b[index + 3] << 24);&nbsp; &nbsp; return Float.intBitsToFloat(l);}
随时随地看视频慕课网APP

相关分类

Java
我要回答