2012-02-29 38 views
2

我想打包时代毫秒到6个字节,但我有问题。我来介绍一下吧:数字类型和按位运算

trace(t); 
for (var i:int = 6; i > 0; i--) { 
    dataBuffer.writeByte(((t >>> 8*(i-1)) & 255)); 
    trace(dataBuffer[dataBuffer.length - 1]); 
} 

输出:

1330454496254 
131 
254 
197 
68 
131 
254 

什么,我做错了什么?

回答

2

我只是猜测,但我认为你的t变量会在位操作生效之前自动转换为int。这当然会破坏价值。

我认为在位操作中不可能使用Number - AS3只支持那些带有int-s的驱动程序。

根据您如何获取t中的值,您可能需要从2 int-s开始,然后从这些字节中提取字节。

+0

=(是的,我将划分它在2个廉政局 – 2012-02-29 18:25:15

2

Number类型是IEEE 754 64位双精度数字,与您的正常int格式完全不同。这些位并不完全相同。什么你要找的是一个正常的64位int类型,当然,这并不在ActionScript 3存在

下面是一个Number对象转换为它的“Int64的”等价功能的ByteArray表示:

private function numberToInt64Bytes(n:Number):ByteArray 
{ 
    // Write your IEEE 754 64-bit double-precision number to a byte array. 
    var b:ByteArray = new ByteArray(); 
    b.writeDouble(n); 

    // Get the exponent. 
    var e:int = ((b[0] & 0x7F) << 4) | (b[1] >> 4); 

    // Significant bits. 
    var s:int = e - 1023; 

    // Number of bits to shift towards the right. 
    var x:int = (52 - s) % 8; 

    // Read and write positions in the byte array. 
    var r:int = 8 - int((52 - s)/8); 
    var w:int = 8; 

    // Clear the first two bytes of the sign bit and the exponent. 
    b[0] &= 0x80; 
    b[1] &= 0xF; 

    // Add the "hidden" fraction bit. 
    b[1] |= 0x10; 

    // Shift everything. 
    while (w > 1) { 
     if (--r > 0) { 
      if (w < 8) 
       b[w] |= b[r] << (8 - x); 

      b[--w] = b[r] >> x; 

     } else { 
      b[--w] = 0; 
     } 
    } 

    // Now you've got your 64-bit signed two's complement integer. 
    return b; 
} 

请注意,它只适用于在一定范围内的整数,它不处理像“不是数字”和无穷大的值。在其他情况下它可能也失败了。

下面是一个使用示例:

var n:Number = 1330454496254; 

var bytes:ByteArray = numberToInt64Bytes(n); 

trace("bytes:", 
     bytes[0].toString(16), 
     bytes[1].toString(16), 
     bytes[2].toString(16), 
     bytes[3].toString(16), 
     bytes[4].toString(16), 
     bytes[5].toString(16), 
     bytes[6].toString(16), 
     bytes[7].toString(16) 
); 

输出:

bytes: 0 0 1 35 c5 44 83 fe 

它应该是在串行数据AS3后来由Java程序读取有用。

家庭作业:写int64BytesToNumber()