Converting an unsigned byte array to an integer
November 29, 2004
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
13 people found this page useful, what do you think?
Trackback Address: 183/DFAFC252C49C29FA6C2ABD5E02FA7ACF
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.
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
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>
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.
Good work dude !!! Thanks I needed it.
This code converts directly from an int to a long.
int i = ...; long l = i < 0 ? 0x0000000100000000L + i : i;
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;
Exactly what I was looking for, thanks!
Thanks guys, just what I was looking for!
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
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'
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
// 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;
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
Search for Free by Name, Business, Address or Phone Number. Accurate!
And how about value & 0xffffffffL????
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.
I get a cash advance from them every few months or so. i highly suggest using them.
Hi, nice very nice page..! http://blog4net.net
Good luck !
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.
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
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.
ISRAELOVE ?????????? ? ??????? ? ??????! (??? ????? ????????? ? ??????? ????? ?????????). www.rap.onemic.co.il
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
????? ?????? ? ???????? ???????!
???????????. ???? ??? ?????????? ??? ?? ????? ????????, ??????? ?????? ?? ??????? ???????? ???????.
??????? ?????!
?? ?????? ?????????? ????????? ????????? ? ?????????? ?? ???????? ? ??????? 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
?? ? ???? ? ??? ???????? ????????, ??? ?????? ?? ?? ? ????? ????? ? ????? ???????? ??? ????? ?????? ?? ?????? (???? ??????????)
????????! ?????!
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
?????? ??? ???? ?????????? ????????? ????? ???- Ric Flair, Scott Steiner, Rick Steiner, Jeff Jarrett, Lex Luger, Buff Bagwell,John Cena , Undertaker,Goldberg & Hulk Hogan & Sting vs. Kevin Nash & Sid Vicious .
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 ????????-?????? ???.
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
You can find here nore than you want
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.
There's a much easier way to do it:
to byte array - BigInteger.valueOf(num).toByteArray()
from byte array - new BigInteger(array).intValue()
Hey guys! CGI/Perl http://www.s-server.net/mod.php?name=Account Cheers!
??? ???? ?? ???????????? ????????? ? ???????????? ??????. ??????????????? ???? ??????????? ? ????? ???????? ?? ????????? ????????????? ?????????? ? ???????????. ?????????? ? ??????????? ?????????????? ???????????? ??????????, ????? ?? ?????????? ??????? ?????????? ? ???????????? ??????, ? ??? ?? ???????????? ??????? ? ???? ??? ????????????? ???????????? ?????? ? ???????. http://building.kh.ua
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.
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
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!
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!
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 }
DUDE .. You saved my day. I am beginner in C C++ and was kind of hit the wall. You saved my night :)
Thanks Alot
gsawyZ http://fgb7s3Ffjsev7yrbvqqcf7.com
?????? ????????-???????? ???????????, ????????? ? ???????? (?????, ???????, ?????, ?????, ???? ? ??.).??????????? ???????. ????????? ?? ????????? www.veles2003.com.ua/tenti.html ??? ??????? 057-7195588 ?.???????.????? ??????! ???????? ??????!
?????? ????????-???????? ???????????, ????????? ? ???????? (?????, ???????, ?????, ?????, ???? ? ??.).??????????? ???????. ????????? ?? ????????? www.veles2003.com.ua/tenti.html ??? ??????? 057-7195588 ?.???????.????? ??????! ???????? ??????!
<b>�� ���� http://warezall.at.ua/ �� ����� ���� ������ ���������� �����������, ��� ���� � ���� ��� ����,����� ������ ��� � ����� �����. ������ ������ �������� ���������� � ���� � ���� ������� ���� ���� ���������� �� ���. ������� ���� �� ���!!!
��������� ��� ���� ���� ����� ������� �� �� ��� ������ � ����� ����� �� ����� ������ ������� � �� ��������� � ���� http://warezall.at.ua/
Hi forum, cool weather and good mood. life is a good thing however turn
Today I discovered the page, looking for famous quotes, which are passionate. In addition to quotes and many other things I found Interesting, that are interested, such as the article on google. I congratulate you for the initiative and I am sure I will return often to the site.
Use imagination and humor. Life opens its doors to you. Expand your game world. Social skills improve and you: learn to collaborate, to play together. I used to group membership and acceptance of others with respect for other people. You learn to trust, to feel comfortable in a safe environment. But first, the game is nice! It's a happy feeling, gives you energy! It makes life feel to the top of your toes! And ... That's why we play!
You learn to conglomerate, to feel undisturbed in a safe environment. But oldest, the heroic is warm-hearted! It's a joyful feeling, gives you vim! It makes life pity to the finish of your toes! And ... That's why we place!jocuri-motociclete.net
Mmm, I wonder if he would like some cheese with that whine?
Between me and my husband we've owned more MP3 players over the years than I can count, including Sansas, iRivers, iPods (classic & touch), the Ibiza Rhapsody, etc. But, the last few years I've settled down to one line of players. Why? Because I was happy to discover how well-designed and fun to use the underappreciated (and widely mocked) Zunes are.
����� � ����������� �������� ���������� ��������� �������� ������� � ������.������������ � ��������. ���������� ������������ http://citypoligraf.kiev.ua/
WHY TO WORRY GUYS..
1.FIRST CONVERT THE BYTE ARRAY TO STING.
2.THEN CONVERT THE STRING TO INTEGER.
EXAMPLE:
byte[] MyByteArray; String Str = new String(MyByteArray); int Value = Integer.parseInt(Str);
Enjoy :)
Moreover, reducing the value or importance of an entity is not always discredit. Many interpretations of the world are not always the worst. Features an event - we know what can be diminished as a result of a reinterpretation not only refers to people or objects. Assumption can be applied to diminish the communication itself. Generalization of the proposed mitigation construct Aptera (1982 - after Wyer & Collins, 1992) may include in its scope a variety of comic phenomena that are very difficult to explain by other theories. By postulating that the reduction is a necessary condition for humor, comic Aptera distinguished changes in interpretation that characterize scientific discoveries, attaching meaning to a person's dreams and reinterpretation of events in the mysterious happenings that occur when new evidence is discovered. In each case, the reality implied by the new information is important or a higher value than the original, and thus is not fun.http://www.jocuri3d.net - jocuri 3d The third important factor Aptera's formulation (1982 - after Wyer & Collins, 1992) is the motivation: the explicit recognition that the objectives of an individual's information processing may play a role in determining individual reactions to information. Aptera has launched the hypothesis that humor has a higher probability of occurrence only when the objectives are to understand the subjects and information to make fun of it. If subjects have a more specific purpose of processing, cognitive activity involved in achieving this goal interferes with understanding the more general processes which produce amusement. Aims to inhibit experiencing one of humor can be induced by external requests to use the information for a particular purpose. They can be induced even information. For example, a joke which contains allusions to an ethnic group can lead to suspicion that the story and its source have the intention to discredit the group. This suspicion can stimulate spontaneously seeking information that confirms the validity of counter-bigotry or discredit the source. Such activity may prevent emergence of humor. Aptera's theory (1982 - after Wyer & Collins, 1992) consider several comic phenomena that can not be explained by other theories. The theory is not restricted to found humor in jokes or stories that are a priori .
Devil on the Mississippi doesn't have any alternate modes of difficulty, and the game offers a lot of little visual nudges in the right direction; items you can pick up give off faint little green glowies, places you can use an item you're carrying give off little blue-white glowies when you mouse over them with the object in hand, and while your skeleton cursor unfortunately doesn't have any glowies of its own, it will change to indicate whenever you're over an area transition or place you can interact with. Keep your eyes peeled for four-leaf-clovers, which will unlock a special play mode, and ravens, which are much more important to you at the present time because they're needed to get hints. Click on the raven sitting atop the lantern in the bottom-left corner during regular gameplay and you'll be pointed towards the next step in your current objective, or you can use a hint during a hidden-object scene to find the item of your choice. Don't use a hint right away, however, since just clicking on an item name in your list will cause the corresponding silhouette to appear in the lantern, and might just give you the clue you need to track it down.http://www.jocuri-motociclete.net/ - jocuri cu motociclete
http://StoneMuscle.at.ua - ????????????? ????. ??????????? ???????????? ?????. ??????? ???? ????? ? ?? ?????????. ?????? Ironman, Muscular Development, Muscle & Fitness, ??????? ??? ?? ???. ???? ?????????????? ??????? ???? ???????????? ?????? ?????? ???? ? ????? ????????? ??????????? ? ????? ?????.
Very nice "unsignedShortToInt" method.
Thanks a million, spent a day or so trying to figure this out!