Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

right-shifting problem

Thread view: 
eli.hen@gmail.com - 18 Dec 2005 06:14 GMT
Hi,

I want to combine 2 different bytes into an integer, so that 1 byte
will be to the left of the second byte.

example:
  byte[2] b;
  b[0] = 0xE5;
  b[1] = 0x35;
I want to get the unsigned number of 0xE535 (=58677), so I did:
  int num = (b[0] << 8) | b[1];
But I got the negative number -6859.

How can I get the desired result (58677)?

-thanks, Eli
eli.hen@gmail.com - 18 Dec 2005 06:28 GMT
Found the solution: ;-)

  int num = (((int)b[0] & 0xFF) << 8) | ((int)b[1] & 0xFF)
Roedy Green - 18 Dec 2005 11:03 GMT
>int num = (((int)b[0] & 0xFF) << 8) | ((int)b[1] & 0xFF)
the int casts are not needed. & 0xff promotes a byte to int.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 18 Dec 2005 11:03 GMT
>example:
>   byte[2] b;
[quoted text clipped - 5 lines]
>
>How can I get the desired result (58677)?
see http://mindprod.com/jgloss/endian.html
http://mindprod.com/jgloss/unsigned.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.