aspose file tools
The moose likes Java in General and the fly likes Byte conversion to number 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 "Byte conversion to number" Watch "Byte conversion to number" New topic
Author

Byte conversion to number

Mike Bates
Ranch Hand

Joined: Sep 19, 2009
Posts: 81
I have a file I am reading in, in binary, and several fields are 24-bit, representing floating point numbers.

For example:
0x300515 = 860.99000

Now, I need to flip the endianess of the number and convert to the number I can use. The byte value is in a byte array defined by

byte[] frequency = {0x30, 0x05, 0x15, 0x00}; // 0x00 added for the flip

In Perl I did this (with help):


The division by 1600 gives me the number 860.9900.

The 'V' means: An unsigned long in "VAX" (little-endian) order. (These 'shorts' and 'longs' are _exactly_ 16 bits and _exactly_
32 bits, respectively.)

and the 'N' means: An unsigned long in "network" (big-endian) order.

I thought I could do this easily in Java but get caught on the pack/unpack parts that were done in Perl and the ultimate conversion to a double.

Looking for direction to wrangle this one.

Thanks
Mike

Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4422
    
    2

Well, fighting big vs little endian stuff is hard. I try really hard to avoid it.

The second problem that you may be seeing is that Java bytes are signed, and there is no concept in Java of an unsigned byte. This normally is noticed when folks are trying to do cryptographic code, since all the the standards are defined on unsigned octets (aka unsigned bytes of 8 bit values).

If you read the file using byte functions, does it work? Reading it 32 bits at a time is likely to lead to madness.
Mike Bates
Ranch Hand

Joined: Sep 19, 2009
Posts: 81
I read the file in fine to a byte array (fairly quick) and I can get to the specific sets of 3 byte values that I need to flip and convert. The issue is trying to flip them correctly and converting to int and/or double so I can use them. I was amazed I was able to read the file in without a problem. See only certain sets of bytes groups represent floating point values and the rest are strings and counters that can be used from the file (and device) without a problem since they are just straight conversions to int or String.

Mike
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Byte conversion to number
 
Similar Threads
Byte order conversion question
Java endian and bit order and signed and unsigned and python and more confusion than I can deal with
JAVA casting bug ? Maybe!
casting problem...from long to byte..
Help required to read binary file