# How to convert int to short?

Discussion in 'Java' started by Muddy Coder, Mar 2, 2009.

1. ### Muddy CoderGuest

Hi Folks,

I searched this group and found an old post showing some about this
topic. Mark Grand wrote the code below:

short s;
byte b1,b2;
b1 = (byte)(s & 0xff); // low order byte
b2 = (byte)(s >>> 8); // high order byte

To convert a short into byte. I got some, but still puzzling on some.
After b1 b2 derived, how to make a new variable with them. Specially,
my goal is to handle a big number:

int pond = 204254242;

I need to convert it into a short. Well, to do this, I must truncate a
part off. In the spirit of the code showing above, I must have 4
bytes:
b1 = .....
b2 = ...
b3 = ....
b4 = ....
I certainly can do this. Then, how can put these b1~b4 together, to
create a new number that can be held in a short? Somebody can help
out? Thanks in advance!

Muddy Coder

Muddy Coder, Mar 2, 2009

2. ### John B. MatthewsGuest

In article
<>,
Muddy Coder <> wrote:

[...]
> Specially, my goal is to handle a big number:
>
> int pond = 204254242;
>
> I need to convert it into a short.

[...]

The value 204254242 requires at least 28 bits to store as a binary
number; a short variable only has room for 16 bits.

If this was not your intent, you may need to clarify your question.

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

John B. Matthews, Mar 2, 2009

3. ### Roedy GreenGuest

On Sun, 1 Mar 2009 16:48:00 -0800 (PST), Muddy Coder
<> wrote, quoted or indirectly quoted someone
who said :

>To convert a short into byte. I got some, but still puzzling on some.
>After b1 b2 derived, how to make a new variable with them. Specially,
>my goal is to handle a big number:

for all your conversion needs, including signed/unsigned byte and
short, see

http://mindprod.com/applet/converter.html

--
Roedy Green Canadian Mind Products
http://mindprod.com

"Learning is not compulsory... neither is survival."
~ Dr. W. (William) Edwards Deming (born: 1900-10-14 died: 1993-12-20 at age: 93))

Roedy Green, Mar 2, 2009
4. ### Andreas LeitgebGuest

Muddy Coder <> wrote:
> short s;
> byte b1,b2;
> b1 = (byte)(s & 0xff); // low order byte
> b2 = (byte)(s >>> 8); // high order byte
> int pond = 204254242;
> I need to convert it into a short.

No need to do it with single bytes. Based on your example
do these replacements:
0xff -> 0xffff
8 -> 16
plus the obvious type-changes (each to it's double-sized)
and you're done.

Andreas Leitgeb, Mar 2, 2009

## Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.