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).


cfobjective pre-conf training

Related Entries

12 people found this page useful, what do you think?

WAF for CF

Trackbacks

Trackback Address: 183/DFAFC252C49C29FA6C2ABD5E02FA7ACF

Comments

On 11/29/2004 at 10:46:47 PM EST 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 EST 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 EST 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 EST 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 EST Rasesh wrote:
5
Good work dude !!! Thanks I needed it.

On 03/15/2005 at 11:08:20 AM EST 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 EDT 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 EDT Jason Arnold wrote:
8
Exactly what I was looking for, thanks!

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

On 08/08/2005 at 9:22:29 AM EDT 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 EST Fernando wrote:
11
Very useful, thank you

On 11/27/2005 at 6:40:27 AM EST 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 EST 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 EDT 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 EDT 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 EDT andreyka wrote:
16
Search for Free by Name, Business, Address or Phone Number. Accurate!

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

On 06/25/2007 at 2:05:09 AM EDT 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 EDT 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 EDT Johny wrote:
20
Hi, nice very nice page..! http://blog4net.net

Good luck !

On 09/15/2007 at 2:18:02 PM EDT 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 EDT 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 EST 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 EST SlamJam wrote:
24
ISRAELOVE ?????????? ? ??????? ? ??????! (??? ????? ????????? ? ??????? ????? ?????????). www.rap.onemic.co.il

On 01/26/2008 at 6:54:57 AM EST 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 EDT 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

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

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

On 06/02/2008 at 8:05:44 PM EDT georgnov wrote:
27
Rehab contractors fixing yours or rental properties and buying unwanted houses in any condition and situation http://www.jerremsproperties.com/forms/customform.cfm?formID=27216 Contractor and friends available for your rehabbing and renovating projects and unwanted houses in any condition: finishing basements and shells , framing and drywall , laminate and tiling , doors and trims , interior and exterior painting , cabinets and bathroom remodelings , ect. Reasonable prices , MHIC#86585 , insured ,bonded, have references,custom design . To see our work please visit our projects photos at (copy and paste on your address bar) http://www.freemyimage.com/ims/album.php?u_id=20787wlky . Also looking for shells or houses to renovate ,we buy unwanted houses in any condition,we take over payments, also preparing houses for selling or renting and proffessional housing provider's help with most house's problems . For selling your house please visit and contact house buying professional (copy and paste on your address bar or click) http://www.jerremsproperties.com/forms/customform.cfm?formID=27216 Contact info : Belspring , phone : 410-978-7981 or e-mail : georgenovitski@yahoo.com. 3105 Bancroft Rd,Baltimore,Md,21215 http://www.rehabhouses.net

On 06/12/2008 at 9:05:28 PM EDT sahokkk wrote:
28
?????? ??? ???? ?????????? ????????? ????? ???- Ric Flair, Scott Steiner, Rick Steiner, Jeff Jarrett, Lex Luger, Buff Bagwell,John Cena , Undertaker,Goldberg & Hulk Hogan & Sting vs. Kevin Nash & Sid Vicious .

On 06/13/2008 at 2:15:31 PM EDT sahokkk wrote:
29
18-year career of former SmackDown Superstar, Undertaker.- Ric Flair, Scott Steiner, Rick Steiner, Jeff Jarrett, Lex Luger, Buff Bagwell,John Cena , Undertaker,Goldberg & Hulk Hogan & Sting vs. Kevin Nash & Sid Vicious . http://www.salazarfill.com/wrestling.htm ????????-?????? ???.

On 06/18/2008 at 2:06:39 PM EDT SuperChesster wrote:
30
If you wish to have a professional shared hosting quality in a free hosting package, come and host with 000webhost.com and experience the best service you can get absolutely free. Founded in December 2006, 000webhost.com has a trusted free hosting members base of over 60,000 members and still counting! Offering professional quality hosting, support, uptime and reliability, we have a great community of webmasters, you'd love to be a part of! Register now and get it all free: *** 350 MB of disk space *** 100 GB of data transfer *** PHP and MySQL support with no restrictions *** cPanel control panel *** Website Builder *** Absolutely no advertising! Join us now: http://www.000webhost.com/40939.html

On 07/22/2008 at 10:09:23 PM EDT pilotaa wrote:
31
You can find here nore than you want

On 07/26/2008 at 4:08:21 AM EDT harrold wrote:
32
Is there a friendship between a man and a woman? I think every asked myself this question. I was confident that exists. After all, I had you, the loyal and reliable friend. And despite the fact that you saw only once, daily telephone conversations, we replaced the meeting. We knew each other absolutely everything, can talk for hours on various topics, often flirtovali and sometimes in your words heard notes jealousy.And even our second halves could not forbid us to communicate. You say that this is fate and our acquaintance on the phone was not accidental. You lived in a nearby town, and several months after dating, we did decide to meet. Brodie all night through the city, chat, kiss. I do not know why we have not decided on any relationship. We just thought that we better stay friends, and almost two years, this was indeed the case.

On 08/12/2008 at 4:50:37 PM EDT Russell Harmon wrote:
33
There's a much easier way to do it:

to byte array - BigInteger.valueOf(num).toByteArray()

from byte array - new BigInteger(array).intValue()

On 09/13/2008 at 10:33:42 PM EDT Sserver wrote:
34
Hey guys! CGI/Perl http://www.s-server.net/mod.php?name=Account Cheers!

On 11/20/2008 at 7:43:40 PM EST building2008 wrote:
35
??? ???? ?? ???????????? ????????? ? ???????????? ??????. ??????????????? ???? ??????????? ? ????? ???????? ?? ????????? ????????????? ?????????? ? ???????????. ?????????? ? ??????????? ?????????????? ???????????? ??????????, ????? ?? ?????????? ??????? ?????????? ? ???????????? ??????, ? ??? ?? ???????????? ??????? ? ???? ??? ????????????? ???????????? ?????? ? ???????. http://building.kh.ua

On 01/22/2009 at 1:05:10 PM EST Inondikeoxike wrote:
36
Applicants under 16 years of age only with court order. The answer has to be YES otherwise the whole world would be divorced. I drew my cheap and really cool pair of sunglasses and my old and broken pair of glasses I use when I'm on the laptop.The missing branch is not a mistake, it's really not there anymore. (There is no waiting period as in most states and marriage licenses are issued and valid immediately and do not expire. Society (?) a less than satisfying union.

On 01/24/2009 at 9:07:58 AM EST cj wrote:
37
Since java version 1.4, use of ByteBuffer makes these conversions easier, keeping the details of the conversion obfuscated. Unfortunately, when reading binary data files one must either know or be able to detect byte ordering, i.e. little/bin endian, for proper conversion.

For example;

import java.nio.ByteBuffer;

public class tt { static public void main(String[] args) throws Exception { byte[] buffer = new byte[55];

// Initialize a network byte order int to 1234 buffer[2] = (byte)0x04; buffer[3] = (byte)0xD2;

// Use ByteBuffer.getInt() to "convert" the byte[] to int int ival = ByteBuffer.wrap(buffer).getInt();

// Print out the value System.out.println("length is " + ival); } // public static void main(String[] args) } // public class tt

On 02/03/2009 at 9:08:53 PM EST dongo2001 wrote:
38
If you have questions on carpets,rugs fur, invite to us to a site www.carpets-fur.com! Here you can learn from many visitors how to buy, how to look after, how to clean carpets,rugs fur. And much-many of experience of other people! Welcome to our website www.carpets-fur.com now!

On 02/05/2009 at 2:18:37 PM EST dongo2001 wrote:
39
If you have questions on carpets,rugs fur, invite to us to a site www.carpets-fur.com! Here you can learn from many visitors how to buy, how to look after, how to clean carpets,rugs fur. And much-many of experience of other people! Welcome to our website www.carpets-fur.com now!

On 05/01/2009 at 8:36:12 AM EDT Amirisetty Vijayaraghavan wrote:
40
You can use java.nio.ByteBuffer of you want to convert an array of bytes into a stream of integers.

ByteBuffer keyBuffer = ByteBuffer.wrap(rowByteArray);

try { int nextInt = keyBuffer.getInt(); // do operations on the integer here } catch(BufferUnderflowException e) { // handle the last 3 bytes }

Post a Comment




  



Spell Checker by Foundeo

Recent Entries





Basecamp
pfreitag on twitter