[英]How can I convert IBM floating point to JavaScript numbers?
I want to read data from in an old file format.我想从旧文件格式中读取数据。 The format uses IBM floating point numbers, and I want to read it in a JavaScript program.
该格式使用IBM 浮点数,我想在 JavaScript 程序中读取它。 IBM floating point representation was used on the IBM System/360 .
IBM 浮点表示用于IBM System/360 。
How can I convert the IBM floating points to JavaScript numbers?如何将 IBM 浮点数转换为 JavaScript 数字?
This function takes a buffer of little endian IBM floats and converts them to a number:此函数采用小端 IBM 浮点数缓冲区并将它们转换为数字:
function ibm2js(buffer) {
var sign = buffer[0] >> 7
var exponent = buffer[0] & 0x7f
var fraction = 0
function bit(buffer, bit) {
return buffer[Math.floor(bit / 8)] >> (7 - (bit % 8)) & 1
}
for (var i = 0; i < 24; i++) {
fraction += bit(buffer, 8 + i) / (2 << i)
}
return (1 - 2 * sign) * Math.pow(16.0, exponent - 64) * fraction
}
Note that special cases like NaN, Infinity, etc. is not covered.请注意,未涵盖 NaN、Infinity 等特殊情况。
This was ported from: http://objectmix.com/perl/21834-ibm-32-bit-floating-point-conversion.html这是移植自: http : //objectmix.com/perl/21834-ibm-32-bit-floating-point-conversion.html
A small update to Hallgrim's solution, which allows to handle double-precision floats: Hallgrim 解决方案的一个小更新,它允许处理双精度浮点数:
function ibm2js(buffer) {
var sign = buffer[0] >> 7
var exponent = buffer[0] & 0x7f
var fraction = 0
function bit(buffer, bit) {
return buffer[Math.floor(bit / 8)] >> (7 - (bit % 8)) & 1
}
var denom = 1
var totalBit = (buffer.length - 1) * 8
for (var i = 0; i < totalBit; i++) {
denom = denom * 2
fraction += bit(buffer, 8 + i) / denom
}
return (1 - 2 * sign) * Math.pow(16.0, exponent - 64) * fraction
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.