Can anybody please tell me how to get double and int value from a binary file. I have tried alot but its giving me wrong values. Here is my code.
InputStream iStream = getApplicationContext().getResources().openRawResource(R.raw.map);
DataInputStream input;
input = new DataInputStream(iStream);
try {
double mapFileFormatVersionNumber, IntendedSoftwareVersion;
int DemoDays;
mapFileFormatVersionNumber =input.readDouble();
IntendedSoftwareVersion = input.readDouble();
DemoDays = input.readInt();
thanks in advance.
Tthere are a gazillion possible representations of integers and doubles. Hence you simply can't expect DataInputStream to be compatible with whatever bizarre binary format. You'll have to go through the specs of .AMF file format and roll your own conversion.
There is no difference in C++ and Java integer types. They are both signed 32-bit numeric types. However, its binary representation might be different depending on the byte order. For example, integer might be represented in file in little endian byte order and reading it assuming it is in big endian will result in wrong data. You might want to experiment with byte order if you don't know exactly how it is stored in the file. Take a look at ByteBuffer Java class, it supports different byte orders.
Related
I was debugging a problem where I created a byte array from binary representation of strings such as below.
While debugging the array just to see how it is stored, I could see them stored internally as decimals. Why is that?
When it gets interpreted as bytecode I am assuming it will get converted as binary. Then why not store in binary in the first place.
String[] binArray = {"10101","11100","11010","00101"};
byte[]bytes = new byte[binArray.length];
for (int i=0; i< binArray.length;i++){
bytes[i] = Byte.parseByte(binArray[i],2);
}
I may be missing something here. Hence request your guidance.
There seems to be a very general misunderstanding.
In some sense, all data is stored "in binary form". Particularly, the integral numerical values, like byte, short, int etc., are internally all stored in binary form. This internal representation is known as the Two's complement form.
(For floating point numbers, the representation is a bit more complicated: It's the IEEE 754 representation - still, they are stored in binary form)
The key issue that has likely lead to your question is: When you just print a number, or convert them to a string, with
System.out.println(someByte);
or
String s = String.valueOf(someByte);
then by default, the decimal form is printed. Mainly because this is the most "natural" and most readable form for humans.
You can pass your bytes to Integer.html#toBinaryString to create the string representation of their binary representation:
System.out.println(Integer.toBinaryString(someByte));
Well, the JVM, just like any program doesn't store numeric values as "decimal" or "hexadecimal". It's just a bit-pattern in memory. Your debugger displays the value in decimal format. This is just for convenience, since most people prefer decimal to binary format for readability. For the computer itself it's just a bit-string of 8 bits length, stored as binary-value.
While debugging the array just to see how it is stored, I could see them stored internally as decimals. Why is that?
You are seeing the byte value displayed in decimal. The debugger is not displaying the internal value.
When it gets interpreted as bytecode I am assuming it will get converted as binary. Then why not store in binary in the first place.
It is stored in binary.
I have a well defined binary data and I want to write Java API for it.
The file format is like
File Signature char[4] 4 bytes
File Source ID unsigned short 2 bytes
Header Size unsigned long 4 bytes
Max double 8 bytes
I am using DataInputStream for parsing the data. char is easy to parse, no problem. But unsigned cannot be parsed correctly. I know Java has no unsigned number. How do I convert it? (Please take unsigned long as example).
EDIT
Here is the code I worte:
File file = new File("lidar.las");
DataInputStream in= new DataInputStream(new FileInputStream(file));
in.skipBytes(6);
long read = (long) (in.readInt() & 0xFFFFFFFFL);
System.out.println("read " + read);
the output is
read 3288596480
my expected number is 1220
.I do not know the code that wrote this binary record, probably in c. All I want is writing a Java version to read data out.
Solved
I am not sure I can answer my own question. LOL
Anyway, Here is the solutions.
private static int getSignedInt( final int unsignedInt ){
ByteBuffer bb=ByteBuffer.allocate(1024*4);
bb.putInt(unsignedInt).flip();
int result =bb.order(ByteOrder.LITTLE_ENDIAN).getInt();
bb.clear();
return result;
}
DataInputStream reads bytes in Big Endian orientation, but check this out:
3288596480 = 0xC4040000
Reversing the bytes, you get 0x04C4 = 1220
You just have to read the values in Little Endian. The question about the sign turns out to be a red herring.
Just read them as short (2 bytes - Java) and int (4 bytes - Java) in your
Java code. You will not lose any information. If you need to output them later,
do a conversion so that you don't output signed numbers.
Given their names: File Source ID and Header Size I doubt you
will do any arithmetic operations on them. If you do, be careful.
Alternatively, you can read them both in long (8 bytes in Java),
and not worry about arithmetic operations as they will not cause issues.
Alternatively, you can read your values as byte arrays in Java,
and then transform them to the proper types in your Java code.
This is probably the most explicit and clean solution.
But it requires more coding.
I have one file created by c++ program which is in encrypted format. I want to read it in my java program. In case of decryption of file contents, decryption algorithm is performing operations on byte[which is unsigned char-BYTE in c/c++]. I used same decryption algorithm which I have used in my c/c++ program. This algorithm contains ^, %, * and - operations on byte. But byte datatype of java is signed because of which I am facing problems in decryption. How can I read file or process read data with 1byte at a time which is unsigned?
thanks in advance.
byte b = <as read from file>;
int i = b & 0xFF;
Perform operations on i as required
The standard method InputStream.read() reads one byte and fits it into a int, so in practice it is an unsinged byte. There are no unsigned primitive data types in java, so the only approach is to fit it in an upper primitive.
That being said you should have no trouble performing encryption/decryption over data bytes read from the file, since the bytes are the same, no matter if they are interpreted as signed or unsigned (0xFF can be 255 or -1). You say the alghorithm contains "^, %, *", etc. That is an interpretation of raw bytes, taking into account a character encoding (that fits 8 bit per character I suppose). You should not perform encryption/decryption operations over other than raw bytes.
First, InputStream.read() returns an int but it holds a byte; it uses an int so -1 can be returned if the EOF is reached. If the int is not -1, you can cast it to byte.
Second, there are read() metods that allow storing the bytes directly in a byte[]
And last, if you are going to use the file as a byte[] (and it is not too big) maybe it would be interesting copying the data from FileInputStream and write it into a ByteArrayOutputStream. You can get the resulting byte[] from the late object (note: do not use the .read() method, use .read(byte[], int, int) for performance).
Since there is no unsigned primitive type in Java, I think what you can do is to convert signed byte into integer (which will virtually be unsigned because the integer will always be positive). You can follow the code in here: Can we make unsigned byte in Java for the conversion.
I have a program that I made in Python to find specific tags in TIFF IFD's and return the values. It was just a proof of concept thing in python, and now I need to move the functionality to java. I think I can just use the String(byteArray[]) constructor for the ASCII data types, but I still need to get Unsigned short (2 byte) and unsigned long (4 byte) values. I don't need to write them back to the file or modify them, all I need to do is get a Java Integer or Long object from them. This is easy in python with the struct and mmap classes, does any one know of a similar way in java? I looked at the DataInput class, but the readUnsignedLong method reads 8 bytes.
DataInputStream allows you to read shorts and longs. You should mask them with the appropriate bit mask (0xFFFF for short, 0xFFFFFFFF for 32 bit) in order to account for the difference between signed/unsigned types.
e.g.
// omits error handling
FileInputStream fis = ...;
DataInputStream stream = new DataInputStream(fis);
int short_value = 0xFFFF & stream.readShort();
long long_value = 0xFFFFFFFF & stream.readInt();
If you're sure that the data won't be towards the high end of the 2 byte field, or 4 byte field, you can forego the bit masking. Otherwise, you need to use a wider data type to account for the fact that unsigned values hold a larger range of values than their signed counterparts.
I looked at the DataInput class, but the readUnsignedLong method reads 8 bytes.
Java does not have unsigned types. It takes 4 bytes to make an int, and 8 bytes to make a long, unsigned or otherwise.
If you don't want to use DataInput, you can read the bytes into byte arrays (byte[]) and use a ByteBuffer to turn those byte values into ints and longs with left padding. See ByteBuffer#getInt() and ByteBuffer#getLong().
DataInput would be the preferred method. You can use readUnsignedShort for the two byte values. For the 4 byte values you'll have to use this workaround...
long l = dis.readInt() & 0xffffffffL;
You could use Javolution's Struct class which provides structure to regions of data. You set up a wrapper and then use the wrapper to access the data. Simples. Java really needs this super-useful class in its default classpath TBQH.
Preon Library is good to create struct in Java. I have tried Javolution's Struct but it was not help full my case. It is open source and very good library.
I am coming across a strange thing. I have a number in binary in the form of string particularly "01001100". But I am getting the exception mentioned above by executing the following code.
String s = "01001100";
byte b = Byte.parseByte(s);
But why is it happening? Whereas in a byte we can store max no. upto 127 and min. upto -128.
And the decimal equivalent of the above number is 76 which is perfectly in the range.
The particular exception I am getting is as:
java.lang.NumberFormatException:Value out of range. value:01001100 radix:10
Is there any way to get rid of it. Yes and it is compulsory for me to use byte only as I am extracting the data stored in the image byte by byte only.
Thank you.
The key is at the end of the exception string: radix:10. You are converting the decimal value 1,001,100 to a byte, and it does not fit. Try this:
String s = "01001100";
byte b = Byte.parseByte(s, 2);
01001100 is a fairly large number in decimal (over a million; see the docs for parseByte(String)). You probably want the version that accepts a radix:
byte b = Byte.parseByte(s, 2);