pf » Converting an unsigned byte array to an integer

Converting an unsigned byte array to an integer

java

I found myself today needing to deal with unsigned integers, and shorts in java. In Java there is no unsigned keyword like in C, or other languages. All primitives are signed (meaning they can hold negative values).

So I came up with two functions for converting the unsigned byte arrays into numbers I can use (thanks to Matt Finn, here at ActivSoftware for some pointers). I am posting these to help others, and to see if anyone knows of a more efficient or easier way to do this:

/**
 * Converts a 4 byte array of unsigned bytes to an long
 * @param b an array of 4 unsigned bytes
 * @return a long representing the unsigned int
 */
public static final long unsignedIntToLong(byte[] b) 
{
    long l = 0;
    l |= b[0] & 0xFF;
    l <<= 8;
    l |= b[1] & 0xFF;
    l <<= 8;
    l |= b[2] & 0xFF;
    l <<= 8;
    l |= b[3] & 0xFF;
    return l;
}
    
/**
 * Converts a two byte array to an integer
 * @param b a byte array of length 2
 * @return an int representing the unsigned short
 */
public static final int unsignedShortToInt(byte[] b) 
{
    int i = 0;
    i |= b[0] & 0xFF;
    i <<= 8;
    i |= b[1] & 0xFF;
    return i;
}

You will notice that the functions actually return a long for unsinged integers, and an integer for shorts, this is because we can't store a large unsigned int in a java int. You may also be interested to know that byte's, short's, and int's are all actually stored using 4 bytes by the jvm (so they can perform 32 bit operations).



Related Entries
7 people found this page useful, what do you think?

Trackback Address: 183/DFAFC252C49C29FA6C2ABD5E02FA7ACF
On 11/29/2004 at 10:46:47 PM MST Keith Lea wrote:
1
You can use my BinaryTools class freely, at http://cvs.sourceforge.net/viewcvs.py/joustim/joscar/src/net/kano/joscar/BinaryTools.java?view=markup

It provides methods for dealing with binary data, including two methods very similar to the two you posted. It uses my ByteBlock class, but you could easily change it (using IDEA's structural search & replace for example) to use byte arrays.

On 11/30/2004 at 1:21:04 PM MST john wrote:
2
if you want it to run at least 8 times slower you can wrap the byte array in a java.nio.ByteBuffer and use its getInt method

On 12/01/2004 at 2:43:35 AM MST Anton wrote:
3
You could try doing it like this. It is basically the same, but much faster. For the unsignedShortToInt, it is about 1/3 faster, where unsignedIntToLong is five times faster. <pre> public static final long unsignedIntToLong(byte[] b) { return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; }

public static final int unsignedShortToInt(byte[] b) { return (b[0] << 8) | b[1]; } </pre>

On 12/01/2004 at 10:42:45 AM MST eu wrote:
4
Shortest version would be (masking to 0xff is necessary):

return ((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16) | ((b[2] & 0xFF) << 8) | b[3] & 0xFF;

You can probably can do some bytecode tweaking to make it bit shorter but not necessary faster.

On 12/03/2004 at 2:21:29 AM MST Rasesh wrote:
5
Good work dude !!! Thanks I needed it.

On 03/15/2005 at 11:08:20 AM MST dave wrote:
6
This code converts directly from an int to a long.

int i = ...; long l = i < 0 ? 0x0000000100000000L + i : i;

On 06/07/2005 at 9:32:14 AM MDT Andre wrote:
7
on my pc (J2SE V1.4.2_04), I have to cast to a long before each operation:

return ((long)(b[0] & 0xFF) << 24) | ((long)(b[1] & 0xFF) << 16) | ((long)(b[2] & 0xFF) << 8) | (long)b[3] & 0xFF;

On 07/06/2005 at 3:18:34 PM MDT Jason Arnold wrote:
8
Exactly what I was looking for, thanks!

On 07/08/2005 at 2:00:53 PM MDT Jason wrote:
9
Thanks guys, just what I was looking for!

On 08/08/2005 at 9:22:29 AM MDT Lee Namba wrote:
10
A probably slower but more flexible way is:

int i = new BigInteger(1,bytes).intValue();

which takes any length array. Especially handy for doing IP filtering for both IPv4 and IPv6

On 11/18/2005 at 6:19:14 AM MST Fernando wrote:
11
Very useful, thank you

On 11/27/2005 at 6:40:27 AM MST Nusli wrote:
12
thanx...

i wasnt '&' it with FF. my code worked because i never tested with values which would give me a -ve int. but looking at this i realized that it had a bug and it sometimes might not work without the '& 0xFF'

On 12/30/2005 at 6:48:29 PM MST Martin wrote:
13
Just another alternative for converting directly from an int (treated as unsigned) to a long:

int i = ...; long res = (i & 0x7FFFFFFF) + ((long)(i>>>31)<<31);

Hope someone (other than me!) finds that helpful

On 06/09/2006 at 2:44:29 PM MDT PMG wrote:
14
// Just an observation ... // The value of uiLong1 after the bit // shifts will be the C++ unsigned int // equivalent of -9999 long uiLong1 = -9999; uiLong1 <<= 32; uiLong1 >>>= 32;

On 06/14/2006 at 7:27:40 AM MDT ibraheem wrote:
15
i'm getting 145 in first byte, tht means 8th bit will be on, when it reaches after shifting on 32th bit, if cozez the signed bit to on, which changes the value...wht'll be the solutiion...thnx in adv

On 05/02/2007 at 2:07:17 PM MDT andreyka wrote:
16
Search for Free by Name, Business, Address or Phone Number. Accurate!

On 06/19/2007 at 2:39:30 AM MDT JM wrote:
17
And how about value & 0xffffffffL????

On 06/25/2007 at 2:05:09 AM MDT joe wrote:
18
As for casting an unsigned short to an int, this is even easier i you have the short to start with: (int)(char)ushort Why does this work? char is the only unsigned numeric primitive in Java.

On 07/02/2007 at 5:40:45 PM MDT Porinasdo wrote:
19
I get a cash advance from them every few months or so. i highly suggest using them.

On 07/27/2007 at 12:02:17 PM MDT Johny wrote:
20
Hi, nice very nice page..! http://blog4net.net

Good luck !

On 09/15/2007 at 2:18:02 PM MDT Jens wrote:
21
There is a difference in little endian and big endian byte order. I had to exchange b[0] and b[1] to get little endian with unsignedShortToInt.

On 10/14/2007 at 6:09:03 PM MDT infoportal3000 wrote:
22
Guys, i've found useful website http://mp3musics.110mb.com/map.html. http://mp3musics.110mb.com/2-pac.html http://www.google.com/search?client=opera&rls=ru&q=2+pac&sourceid=opera&ie=utf-8&oe=utf-8 http://mp3musics.110mb.com/50-cent.html http://www.google.com/search?num=100&hl=ru&client=opera&rls=ru&hs=8Nj&q=50+cent&btnG=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA&lr= http://mp3musics.110mb.com/Linkin-Park.html http://www.google.com/search?num=100&hl=ru&client=opera&rls=ru&hs=JkO&q=linkin+park&btnG=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA&lr= http://mp3musics.110mb.com/Justin-Timberlake.html http://cars4you.1sthost.org/cars-online/index.html http://cars4you.1sthost.org/buy-used-cars/index.html http://cars4you.1sthost.org/buy-cheap-cars/index.html http://cars4u.ifastnet.com/buy-used-cars/index.html http://cars4u.ifastnet.com/online-cars/index.html

On 12/19/2007 at 6:29:54 AM MST joaedmonds wrote:
23
Hello, Can you help me to find The best soft to PC-where to buy, join site & other tipe to do a home online business. Thanks.

On 01/24/2008 at 12:36:28 PM MST SlamJam wrote:
24
ISRAELOVE ?????????? ? ??????? ? ??????! (??? ????? ????????? ? ??????? ????? ?????????). www.rap.onemic.co.il

On 01/26/2008 at 6:54:57 AM MST VaddyRonadego wrote:
25
Hi So I was browsing around Camazon last night before I went out with a bunch of my buddys to go bowling and drink a couple beers and I stumbled upon a pretty cute little Asian chick who was currently online so I hit her up and we started chatting. Evidently she lives right next to the bowling alley we were all going to and I invited her to come join us for some beer and bowling. http://www.american5.happyhost.org/24bb48/ - big breasts http://www.american5.happyhost.org/a4e894/ - breasts http://www.american4.happyhost.org/03c399/ - men s breasts http://www.american4.happyhost.org/5e5698/ - breasts milk http://www.american3.happyhost.org/74860f/ - big breasts natural http://www.american3.happyhost.org/d445cd/ - milk breasts http://www.american2.happyhost.org/1db6f9/ - breasts lactating http://www.american2.happyhost.org/2556a4/ - lactating breasts http://www.american1.happyhost.org/f3171a/ - milky breasts http://www.american1.happyhost.org/9602a3/ - bigger breasts I invited her back to my flat to come hang out for a bit and she accepted my offer almost instantly. I drove us back to my place and we sat down and I grabbed a couple beers as we talked some more. We bowled for a good two hours and talked quite a bit while my friends all starred at me like I was the luckiest guy there! When it comes time to leave to head on home, she gave me a hug and a kiss then asked me what I had planned for the rest of the night. G'night

On 03/24/2008 at 5:54:41 PM MST Real256 wrote:
26
????? ?????? ? ???????? ???????!

???????????. ???? ??? ?????????? ??? ?? ????? ????????, ??????? ?????? ?? ??????? ???????? ???????.

??????? ?????!

?? ?????? ?????????? ????????? ????????? ? ?????????? ?? ???????? ? ??????? 30 ??????.

?? ???????? 0.01 $ ?? ?????? ???????? ????????,

? ??? 0.01 $ ??? ?????? ???????? ???????? ????? ?????????.

????? ?? ????? ????? ????? 10$ ?? ?????? ????????? ?? ? Alertpay ? ????? ?? ????????(???????? Visa classic(????? ????? ?????? ? ????? ????? ? ????? ??? "???????")), ??? ????????? ? E-Gold ??????, ? ????? ?? ??????? webmoney

?????? ?????? ??? ?????????????? 20 ?????? ? ???? = 0.20 $ ?10 ????? ????????? ??????? 20 ?????????? ? ???? = 2.00 $ ???? ?????????? ????? = 2.20 $ ???? ???????????? ????? = 15.4 $ ???? ??????????? ??????????? ????? = 66.00 $ ????? ?? 5-10 ????? ? ????!

????????? ?????????? ?? ??????????? ?? ?????? ??????? ?? ???? ?????? http://depositfiles.com/files/4230145

?? ? ???? ? ??? ???????? ????????, ??? ?????? ?? ?? ? ????? ????? ? ????? ???????? ??? ????? ?????? ?? ?????? (???? ??????????)

????????! ?????!




  



Spell Checker by Foundeo





Subscribe to my RSS Feed: solosub RSS
Tags