Hey

I was wondering how I could write a binary file in Java with code in C++ using the reinterpret_cast function. If I remember the line correctly (not currently at work) it was:

file.write=reinterpret_cast<char *(&x)>,sizeof x;

with x being a variable.

How can I do that in Java? From reading around, many topics said I should make the class Serializable. Would it be something like this?

public class anumber implements Serializable 
{
       private int x; /*Not sure if that is the correct way as I am not doing it in a IDE to declare it but know what i mean*/
        
       public int getx()
        {
            return x;
        }

       public void setx(int y) //y being the variable i pass to this function
        {
           this.x=y;
         }

}

then in another class

public class whatever
{
    public void main()
    {
       anumber b=new anumber();
      /*NEEDS HELP FROM THIS POINT TO WRITE THE NUMBER/VARIABLE x TO A BINARY FILE*/
    }
}

Where I comment "/*NEEDS HELP FROM THIS POINT TO WRITE THE NUMBER/VARIABLE x TO A BINARY FILE*/" is obviously where I am stuck. Do I write the object b directly using the OutputStreamWriter (I belive it is) or do i use b.getx() and write that?

From what Ive been told the C++ code write bytes such as this:

10101010
11111111
92839423

from integers into the binary file.

How do I do this in Java giving the same output as the C++ program? Thank you

BTW: this is what reinterpret_cast does:

http://msdn.microsoft.com/en-us/library/e0w9f63b(v=VS.100).aspx

Recommended Answers

All 59 Replies

Starting with a Serializable object, you can write it to an ObjectOutputStream with a single write, and read it back from a corresponding ObjectInputStream ditto.

NB: The JavaDoc for many classes warns that the serialisation format may change from one release of Java to another, so its not suitable for writing files for long-term storage of data, but it's OK for short-term storage or sending Objects over TCP/IP sockets etc.
For a safer and more comprehensible approach, have a look at XMLEncoder and XMLDecoder. These utility classes convert Objects with standard getter/setter methods into a simple XML format that you can safely write/read/send just like any other pure text file.

How do I do this in Java giving the same output as the C++ program?

Can you look at the file the C++ program generates with a hex editor?
If the contents of the file are the bytes for an int variable, a java program can write out the same bytes as a C++ program.

OK, looking at Norm's post I may have answered the wrong question.
Do you want to write objects to a (binary) file in a Java way, or do you want to mimic exactly the same sequence of bits that your C++ code would have written?
I previously answered the first of those.
For the second answer you can use a DataOutputStream and its methods like writeInt, writeBytes etc to write individual primitive values in their normal binary formats, but you will have to do as Norm says to confirm whether that's exactly what the desired format is.

Thank you for the replies

Starting with a Serializable object, you can write it to an ObjectOutputStream with a single write, and read it back from a corresponding ObjectInputStream ditto.

NB: The JavaDoc for many classes warns that the serialisation format may change from one release of Java to another, so its not suitable for writing files for long-term storage of data, but it's OK for short-term storage or sending Objects over TCP/IP sockets etc.
For a safer and more comprehensible approach, have a look at XMLEncoder and XMLDecoder. These utility classes convert Objects with standard getter/setter methods into a simple XML format that you can safely write/read/send just like any other pure text file.

The files are short-term storage (as a matter of fact, they are one time usage almost)

From the other post (later on, which I also quote), not sure if you understood me correctly.

Can you look at the file the C++ program generates with a hex editor?
If the contents of the file are the bytes for an int variable, a java program can write out the same bytes as a C++ program.

The C++ generates other data but mainly those integers which can be read by a PLC. Im not sure if seeing it with a hex editor will clear up things or not but ill try it out.

OK, looking at Norm's post I may have answered the wrong question.
Do you want to write objects to a (binary) file in a Java way, or do you want to mimic exactly the same sequence of bits that your C++ code would have written?
I previously answered the first of those.
For the second answer you can use a DataOutputStream and its methods like writeInt, writeBytes etc to write individual primitive values in their normal binary formats, but you will have to do as Norm says to confirm whether that's exactly what the desired format is.

(Exactly what I want to do: ) I want to write a array of ints to a binary file.

I did indeed try the writeint (using a for, since there is no write array of int) and writebtyes (using conversions) methods but they were not correctly generated in the bin file.

OK, sorry about the confusion. writeInt in a for loop sounds right. Can you post the exact code? Remember that Java ints are 4 bytes, not 2. For a 2-byte int you need a "short".
Maybe you can post the original int array values, and a hex dump of what you expected and what you actually got in the file. That would allow us to home in on the correct solution.

OK, sorry about the confusion. writeInt in a for loop sounds right. Can you post the exact code? Remember that Java ints are 4 bytes, not 2. For a 2-byte int you need a "short".
Maybe you can post the original int array values, and a hex dump of what you expected and what you actually got in the file. That would allow us to home in on the correct solution.

Wow that could be a big hint.
So in C++ ints are 2 bytes and in Java they are 4 bytes? Did not know this and it could be a important step.

How about double in Java? Any different byte sizes with double/float/etc in C++?

This is for where I work so Im going to have to get back to you on that on Monday.

Tried with the writeShort method and still didnt work. (gave me a 4 byte file which didnt work)

He uses this to write:

std::ofstream myfile(str_file.c_str(), ios::out|ios::trunc|ios::binary);
str_file is the name of the file to store, for example C:\\x\\fileofbin.bin
myfile.write(reinterpret_cast<char*>(&x_1),sizeof x_1);

I am trying a array of integers from 0 to 14 (the positions) with just some ints such as

11111111;
11112111;
11234111;
22222222;
0;
-11111112;
69384959;
10;
1;
55555555;
10101010;
88888888;
-98765432;
-9;
1;

All these are stored in a array, I go thru the array with a for (in most logical cases) and write them to a binary file.

Things Ived tried:

(In this example I did this:

Object obj=new Object();
obj=array;

That explains that attempts with obj
)

/*1*/    //	data_out.writeByte(enteros[i]);
/*2*/    //	data_out.writeByte(Integer.parseInt((String)obj));

		    	
/*3*/    //	data_out.writeBytes(String.valueOf(array[i]));
/*4*/    //	data_out.writeBytes((String)obj);
		    	
/*5*/   //	data_out.writeObject(obj);
/*6*/   //	data_out.writeObject(array[i]);
		    	
		
/*7*/  //	data_out.writeObject(array); 
/*8*/ //data_out.writeShort(array[i]);

(enteros is array; Messed up when changing the name in the post sorry)

Please tell exactly what the correct contents of the file should be, in hex.

Please tell exactly what the correct contents of the file should be, in hex.

Ill try to get that to you ASAP. He didnt come to work today (I dont think he is coming any day today: There is a holiday tommorow, thursday and friday)

I suppose that the attached file is what you want

? attached?

Yes. There is a attached PNG. You dont see it?

No I don't. Maybe it's just me. My wife's always telling me I can't see things in front of my nose. Can anyone else out there see it???

Ill put it on imageshack. One second....

Now you need to show the values that were written to create the bin file.

So, your first 4 values are 11111111 11112111 11234111 22222222 ...
and the file begins (in hex bytes) 14,00,00,00,28,00,00,00,D8,8A,01,00 ...

Sorry, but I can't see any connection between those two. I have no idea how those integers are encoded into that hex.
Maybe we can go to something simpler, like writing the values 1,2,3 to a new file from the C++ program and dumping the resulting file?

Now you need to show the values that were written to create the bin file.

This is the bin file used to generate what I believe is a BMP (Dont quote me on that) of a picture of 2 horizontal pieces and 2 vertical pieces of a rectangule (splitting it up into 4 pieces)

Like I mentioned I believe, the C++ program does calculation for this (and alot more things) but for now I simply want to make a bin file with a array full of int numbers.

So, your first 4 values are 11111111 11112111 11234111 22222222 ...
and the file begins (in hex bytes) 14,00,00,00,28,00,00,00,D8,8A,01,00 ...

Sorry, but I can't see any connection between those two. I have no idea how those integers are encoded into that hex.
Maybe we can go to something simpler, like writing the values 1,2,3 to a new file from the C++ program and dumping the resulting file?

Yes. Thank you :) Ill explain.

Those 8 digit numbers such as "11111111" and "11112111" are signals for a machine. Example:
11111111 might mean to stop the machine
11112111 might mean to start the machine
11231211 might mean to emit a sound

Thats why my array (like I mentioned) are:

array[1]=11113333;
array[2]=11114444;
array[3]=99999999;

and so forth. I just need to know how to do that in Java. Nothing more, nothing else. Write a array full of 8 digit numbers to a .bin file.

The problem is your original post said "How do I do this in Java giving the same output as the C++ program?".
Without that constraint, writing Java ints to a bin file is trivial.
This being a Java forum you can't assume that we know how C++ writes binary files.

BMP picture or machine instructions? Am I the only one who is confused?

The problem is your original post said "How do I do this in Java giving the same output as the C++ program?".
Without that constraint, writing Java ints to a bin file is trivial.
This being a Java forum you can't assume that we know how C++ writes binary files.

My mistake :)

(For now), I just want to write from Java the int numbers in a array to a bin file. Thats it.

I apoligize for any misunderstanding.

BMP picture or machine instructions? Am I the only one who is confused?

Machine instructions. Like I said, dont quote me on that as I could not confirmed it until you said that it contained "11112222" and numbers like that.

Sorry about that confusion.

DataOutputStream and writeInt(...)

We need to see how the C++ program writes a few known integer values to a file.
When we see the order of the bits in the file for the known integers, we can write the java code to write the bits for the same numbers to a file in the same order.
For example if C++ writes the int value 20 to a file and the bits in the file are 1400
for that number than we can write a Java program that will write the same bits for the number 20.
We must have samples for several numbers from small numbers to large numbers.

DataOutputStream and writeInt(...)

Will retry now DataOutputStream and writeint even though like someone mentioned it might be short because int in C++ has 2 bytes and in Java it is 4 bytes, correct?

We need to see how the C++ program writes a few known integer values to a file.
When we see the order of the bits in the file for the known integers, we can write the java code to write the bits for the same numbers to a file in the same order.
For example if C++ writes the int value 20 to a file and the bits in the file are 1400
for that number than we can write a Java program that will write the same bits for the number 20.
We must have samples for several numbers from small numbers to large numbers.

The C++ program writes more than just ints. We are writing a array of ints as a test to see if the PLC will read it. From then on forward, we can write more things. We are only going to write numbers, especifically from what I have been told ints and doubles (floats).

The order is already computed by the C++ program (which is being rewritten in Java by parts. The order of those parts I cannot determine as they give us chunks of code, not in any particalur design or order).

From what I gather, he simply writes the number as is, not using 24 bits from the number 11111111 or 30 bits for the number 22222222. Nothing special.

Nothing special.

Computers are very fussy about the location and order of bits.
Are there any programmers where you are that we can talk to about your problem?

Computers are very fussy about the location and order of bits.
Are there any programmers where you are that we can talk to about your problem?

Besides ourselves :P no. Thats another problem; We cant see their C++ code (even if we dont understand C++) and start writing and when something comes up that we dont understand, ask. Its limited and antiproductive. Right now, besides this, we having to do and you know the saying: Time is money. We have noone to report to right now so, here we are stuck.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.