aspose file tools*
The moose likes Beginning Java and the fly likes An Int To a Byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "An Int To a Byte" Watch "An Int To a Byte" New topic
Author

An Int To a Byte

amal shah
Ranch Hand

Joined: May 05, 2006
Posts: 92
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

Joined: Aug 21, 2007
Posts: 21
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?


http://dredwerkz.ic.cz
amal shah
Ranch Hand

Joined: May 05, 2006
Posts: 92
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

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13884
    
  10

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: An Int To a Byte
 
Similar Threads
inconsistent behavior with byte
Is there a easy way to find the solution?
Serious Conversion Problem - Please HELP
(byte) and 0xff
Trouble Converting from Int Array to Byte Array