2016-08-02 117 views
1

得到某些字節所以我有一個方法,採取整數n,和兩個長xy。它應該從x返回第一個n字節,其餘的從y返回。看起來很簡單,但我是新的直接與字節工作,並不能讓這種方法工作。爪哇從長

public static long nBytesFromXRestY(int n, long x, long y) { 
    int yl = longToBytes(y).length; 
    byte[] xx = new byte[yl]; 
    byte[] xa = longToBytes(x); 
    byte[] yb = longToBytes(y); 
    for (int i=0;i<xx.length;i++) { 
     if (i < n) { 
      System.out.println("i < n"); 
      xx[i] = xa[i]; 
     } else { 
      xx[i] = yb[i]; 
     } 
    } 
    System.out.println(Arrays.toString(xx)); 
    return bytesToLong(xx); 
} 

如果我喂的是方法n = 3x = 45602345y = 10299207,它應該返回45699207(右..?),但它會返回10299207 ..

它打印"i < n"三次,所以我知道for和if/else正在工作。但由於某種原因,它仍然只返回yb陣列。對不起,如果這是一個愚蠢的問題。對我來說新概念。

編輯:longToBytesbytesToLong方法:

public static long bytesToLong(byte[] bytes) { 
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); 
    buffer.put(bytes, 0, bytes.length); 
    buffer.flip();//need flip 
    return buffer.getLong(); 
} 

public static byte[] longToBytes(long x) { 
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); 
    buffer.putLong(0, x); 
    return buffer.array(); 
} 
+0

你似乎混淆了字節與數字。在你想要的輸出中,你需要'x'的前3位數字,其次是'y'的其餘部分。 – Tunaki

+0

好的,我有一種感覺就是這樣。那麼,如果我給它提供相同的數字並且它使用前3個字節而不是數字,那麼該方法將返回什麼呢? – isaac6

+0

您的結果正是如此。打印'longToBytes(45602345)'和'longToBytes(10299207)',你會發現第一個3都是0. – Tunaki

回答

1

可以使用bitshifting而不是創建對象。

public static long nBytesFromXRestY(int n, long x, long y) { 
    long mask = ~0L << (n * 8); 
    return (x & mask) | (y & ~mask); 
} 

這將返回y的最低n * 8位和x的高位。如預期

http://ideone.com/1CkqYT

打印。

45299207   
+1

太棒了,謝謝。似乎是一個更好的方法來做到這一點。有時間去做一些閱讀比特運算符.. – isaac6