| Author |
Concatenate two bytes
|
Jason Fox
Ranch Hand
Joined: Jan 22, 2004
Posts: 114
|
|
I'm not sure how to do this, so I thought I'd ask here, I'm digging through and doing research, but right now I'm pretty stuck. Here's what I need to do: take to bytes, concatentate them together (not add), for example, so that (byte)0x40 and (byte)0xFF become (short)0x40FF. If I try to concatenate the two bytes as strings, I get a completely wrong number (32 bit, obviously an int, and a cast to short doesn't help). Also, the bytes are coming in decimal format, but I need the short in hex, (though, as long as the bits are the same, it shouldn't matter). I seem to remember a quick and easy way to do this, though I could be wrong. Thanks.
|
 |
Dan Chisholm
Ranch Hand
Joined: Jul 02, 2002
Posts: 1865
|
|
|
Move one byte to a variable of type short, shift it 8 bits to the left, and then "or" it with the other byte.
|
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
|
 |
Jason Fox
Ranch Hand
Joined: Jan 22, 2004
Posts: 114
|
|
Thanks for the help. I hope my addled brain is simply misunderstanding your algorith, but I'm getting a strange response (-28672, where I expect to see 36864). Here is the method: BTW, the two byte parameters are coming from a DataInputStream's readByte() method. [ June 29, 2004: Message edited by: Jason Fox ] [ June 29, 2004: Message edited by: Jason Fox ]
|
 |
Jason Fox
Ranch Hand
Joined: Jan 22, 2004
Posts: 114
|
|
|
nevermind, it would appear that the binary for -28672 is identical to the binary for 36864. I am now thoroughly confused. The leftmost bit is a one, so how can the number be simultaneously signed/unsigned?
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24043
|
|
Shorts are signed integers, and the largest positive value is 32767 (2^15-1); anything largest than that and it "wraps around" to a negative number. If you have a short whose bit pattern represents an unsigned 16-bit number, you can get the non-negative integral value like this: int nonNegativeValue = shortValue & 0xFFFF;
|
[Jess in Action][AskingGoodQuestions]
|
 |
Jason Fox
Ranch Hand
Joined: Jan 22, 2004
Posts: 114
|
|
|
Thanks, I completely 'forgot' that 36864 is larger than signed 16 bits can hold. Its been one of those days. However, knowing how to store/retrieve an unsigned integer in java is going to come in very handy soon, so thanks very much.
|
 |
 |
|
|
subject: Concatenate two bytes
|
|
|