File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "An Int To a Byte" Watch "An Int To a Byte" New topic

An Int To a Byte

amal shah
Ranch Hand

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

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?
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
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: 15081

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 8 API documentation
I agree. Here's the link:
subject: An Int To a Byte
It's not a secret anymore!