isaac6 isaac6 - 4 months ago 10
Java Question

Java getting certain bytes from a long

So I have a method that takes an int (n), and two longs (x) (y). It should return the first (n) bytes from (x), and the rest from (y). Seems simple enough but I am new to working directly with bytes and cannot get this method to work.

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);
}


If I feed that method n=3, x=45602345, and y=10299207, it should return 45699207 (right..?) but it will return 10299207.. It prints "i < n" three times so I know the for and if/else are working. Yet for some reason it still just returns the 'yb' array. Sorry if this is a stupid question..new concept for me.

EDIT: longToBytes and bytesToLong methods;

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();
}

Answer

You can use bitshifting instead of creating objects.

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

This will return the lowest n * 8 bits of y and the higher bits of x.

http://ideone.com/1CkqYT

Prints as expected.

45299207