• Post Reply Bookmark Topic Watch Topic
  • New Topic

Read C structure in java  RSS feed

 
Colin Bester
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am needing to read a binary file from disk which is created with a 'C' application. All contents of the file are floats.
Is there any conversion routine to enable me to read these four bytes into a java float?
(Or suggestions)
Thanks,
Colin
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Colin,
What C method are you using to dump the floats to the file and what OS/hardware is the file created on? If you're sure of the byte order then you should be able the use the static method float Float.intBitsToFloat(int bits) to reconstruct them for you. This method uses the IEEE 754 floating-point "single format" bit layout. You'll obviously have to create the int with the four bytes before passing it in but that shouldn't be a big deal.
To read in the file, I would suggest using a FileInputStream and calling the read(byte[] buf) method where buf is a 4 member array. Just setup a loop like:

Hope this helps,
Michael Morris
 
Colin Bester
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks appreciate the input. I must have looked a dozen times at the api's and didn't 'see' the int to float function. All working smoothly now.
Colin
 
Gopi Balaji
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Colin,
Out of curiosity, what is the byte order of data in the file? Does that machine have an Intel/DEC chip, or any other?
-GB.
 
Colin Bester
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The data is created on an Intel machine where the lsb is stored first. i.e. 0x01020304 is store in memory as 04,03,02,01 (Little Endian). In my code I swopped these around and made a new number which I passed to IntBitsToFloat to get my float value.
Trust this helps.
Colin
 
Gopi Balaji
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Colin Bester:
The data is created on an Intel machine where the lsb is stored first. i.e. 0x01020304 is store in memory as 04,03,02,01 (Little Endian). In my code I swopped these around and made a new number which I passed to IntBitsToFloat to get my float value.
Trust this helps.
Colin

Thanks.
-GB.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!