File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

An Int To a Byte

 
amal shah
Ranch Hand
Posts: 92
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
My basic aim is to convert an int to a byte...the simplest way out is to cast it....other way i checked on google is to use shift operators.....there are a lot of codes there....but could not get the point as to how it should be done.....

help appreciated
cheers
amal shah
 
Jiri Goddard
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, so why don't you try to cast it then? or are you looking for some "faster" way how to do it, e.g. the bit shifting?
 
amal shah
Ranch Hand
Posts: 92
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i want to try a different way of doing it.......pls if someone could explain me the process involved in it...i tried but could not understand the concept behind it....

help appreciated
cheers
amal shah
 
Peter Chase
Ranch Hand
Posts: 1970
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your int contains a value in the range for a byte, -128 to 127, then just casting it is fine. I can't see how anything else could be better or quicker.

If your int contains a value outside that range, then it cannot be represented by a single byte(*). Maybe you then want the four bytes that would represent any int value. Something like: -



You might like it the bytes in the other order, which I hope you can see is trivial.

(*) if you want unsigned, then I suppose the range is 0 to 255. This gets complicated, though, because Java bytes are signed.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that to convert an int to a byte, there is no other way than to use a cast. You can use shift operators to pick out certain bits in the int that you want to put into the byte, but you still have to cast the result to be able to put it into a byte. Peter's example above also contains casts, as you can see.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic