Velocity Reviews > Java > How to convert int to short?

# How to convert int to short?

Muddy Coder
Guest
Posts: n/a

 03-02-2009
Hi Folks,

topic. Mark Grand wrote the code below:

short s;
byte b1,b2;
b1 = (byte)(s & 0xff); // low order byte
b2 = (byte)(s >>> ; // 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

Muddy Coder

John B. Matthews
Guest
Posts: n/a

 03-02-2009
In article
<(E-Mail Removed)>,
Muddy Coder <(E-Mail Removed)> 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

Roedy Green
Guest
Posts: n/a

 03-02-2009
On Sun, 1 Mar 2009 16:48:00 -0800 (PST), Muddy Coder
<(E-Mail Removed)> 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

--
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))

Andreas Leitgeb
Guest
Posts: n/a

 03-02-2009
Muddy Coder <(E-Mail Removed)> wrote:
> short s;
> byte b1,b2;
> b1 = (byte)(s & 0xff); // low order byte
> b2 = (byte)(s >>> ; // 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.