How to convert int to short?

M

Muddy Coder

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
 
J

John B. Matthews

[...]
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.
 
R

Roedy Green

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

Andreas Leitgeb

Muddy Coder said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top