0

As part of a program I'm writing I need to consolidate two bytes into a long from an array of bytes. So assuming this:

byte a[] = new byte[2]
a[0] = 0b1000111
a[1] = 0b1111000

how can I consolidate them such that

long b = 0b10001111111000

EDIT: The program will attempt to consolidate anywhere between 2 bytes and 100, just for reference.

getynge
  • 135
  • 1
  • 7

3 Answers3

1

In order to combine those two bytes you will only need 16 bits. A short will suffice:

short result = (short)(((a[0] & 0xff) << 8) | (a[1] & 0xff))

If for some reason, you need the long data type, you need only replace the cast with a long.

Joel
  • 4,732
  • 9
  • 39
  • 54
  • @GlennLane How exactly does this work? I like knowing what goes on behind a solution before I use it. Thanks! – getynge Nov 13 '13 at 01:10
  • @muttstuffle What this does is it takes the first byte and shifts it so that it is the first 8 bits of a short. Then we OR the second byte with that to make it the last 8 bits of the short. So we have a 16 bits containing both of the bytes – Joel Nov 13 '13 at 01:17
  • 1
    Sorry @Joel, your solution works. Mind though, if a[0] is negative (-90 or 0xa6), then (short)a[0] gives 0xffa6 (not 0x00a6)... but you're shifting those ff's away so it doesn't matter. It **would** matter if you were using a wider type like int or long however, in which << 8 would give you 0xffffa600 for int. – Glenn Lane Nov 13 '13 at 01:27
  • @GlennLane Good point. Stupid java and its lack of unsigned types. – Joel Nov 13 '13 at 01:30
  • @Joel now there's a problem... you're implying a cast on a[1]. If a[1] is negative, you're or'ing 0xffffffffffffff??. You need to mask a[1] as well. – Glenn Lane Nov 13 '13 at 01:38
  • ... and the cast on a[0] is unnecessary because it becomes long after and'ing with mask – Glenn Lane Nov 13 '13 at 01:42
  • ((a[0] & 0xffL) << 8) | (a[1] & 0xffL) ;-) – Glenn Lane Nov 13 '13 at 01:44
  • @GlennLane Right, should be good now. Thanks for that, I am just so used to unsigned types! Ha – Joel Nov 13 '13 at 01:47
  • And the short snippet won't compile... bitshifting always returns at least an int, never a short, so you would need to cast after shifting. As well, your a[1] would bring in 0xff?? if it were negative. Try: (short)(((a[0] & 0xff) << 8) | (a[1] & 0xff)) – Glenn Lane Nov 13 '13 at 01:54
1

java.nio can do that:

ByteBuffer.wrap(a).getShort()
Glenn Lane
  • 3,892
  • 17
  • 31
1

BigInteger can do this: http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html

BigInteger buffer = new BigInteger(yourByteArray);
long result = buffer.longValue();

Note that if your byte array has a value larger than a long (eg, you mentioned that you might go up to 100 bytes), toLong() will only return the value of the lower value bytes. BigInteger, however, will handle any arbitrary number of bytes.

bstempi
  • 2,023
  • 1
  • 15
  • 27