This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes how to convert byte array into short?? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "how to convert byte array into short??" Watch "how to convert byte array into short??" New topic
Author

how to convert byte array into short??

salman khan
Greenhorn

Joined: Mar 20, 2008
Posts: 4
how to convert byte array into short
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
In the general case, this is impossible. A byte array can contain any amount of data, whereas a short contains exactly 16 bits.

What's in the byte array?

And do you mean a short array, rather than a short?


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3670

You will have to copy the content in to a short array by going through the elements of the byte array.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 434

Hi,

Like Peter mentioned it could result in a possible loss of data depending on the size (no. of bits big) your data is. You can do it by iterating through the elements of the array and down-casting them.

Cheers,
Raj.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32687
    
    4
Down-casting? Isn't it the other way round; byte to short is a widening conversion?
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Campbell Ritchie:
Down-casting? Isn't it the other way round; byte to short is a widening conversion?


Yes, but the original poster said he wanted to convert a "byte array" to a "short", not to a "short array".

If converting to a short array, there is no risk of data loss, as you say.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32687
    
    4
He did, but I am presuming (as you did) he meant short[]. And Raj Kamal did say iterate before downcasting so it would be byte->short.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: how to convert byte array into short??
 
Similar Threads
Convert Object to byte array and array size should be 40
Xml Element to Byte Array
byte array to bits
byte[] to blob
Convert Object to byte array and array size should be 40