2012-02-29 68 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()