How to convert int/float etc into byte[]?

R

RC

For example

int i = 2;
char c = 'c';
float f = (float)3.45;
double d = 3.546;
String s = "Hello";

I want to write all these into a binary file.

In OutputStream, PrintStream classes
they have

write(int byte); and
write(byte[] buffer, int offset, int length);

My question is how do I convert those i,c,f,d,s into
byte[]?

Thank Q in advance!
 
P

Patricia Shanahan

RC said:
For example

int i = 2;
char c = 'c';
float f = (float)3.45;
double d = 3.546;
String s = "Hello";

I want to write all these into a binary file.

In OutputStream, PrintStream classes
they have

write(int byte); and
write(byte[] buffer, int offset, int length);

You can do it either the easy way, or the hard way.

The easy way is to wrap your OutputStream in a DataOutputStream and use
its writeInt, writeChar, writeFloat etc.
My question is how do I convert those i,c,f,d,s into
byte[]?

That would be the hard way. Do you still want to know?

Patricia
 
R

RC

Patricia said:
RC said:
For example

int i = 2;
char c = 'c';
float f = (float)3.45;
double d = 3.546;
String s = "Hello";

I want to write all these into a binary file.

In OutputStream, PrintStream classes
they have

write(int byte); and
write(byte[] buffer, int offset, int length);

You can do it either the easy way, or the hard way.

The easy way is to wrap your OutputStream in a DataOutputStream and use
its writeInt, writeChar, writeFloat etc.

Thank Q, I'll try that.

I tried this

Float ff = Float.valueOf((float)3.2);
byte b = ff.byteValue();

outputStream.write(b);

Is this make sense?

It is not make too much sense to me, because how do I know the
size of byte array (b)?
My question is how do I convert those i,c,f,d,s into
byte[]?

That would be the hard way. Do you still want to know?

Patricia
 
R

Roedy Green

B

Ben Phillips

Patricia said:
The easy way is to wrap your OutputStream in a DataOutputStream and use
its writeInt, writeChar, writeFloat etc.
My question is how do I convert those i,c,f,d,s into
byte[]?

That would be the hard way. Do you still want to know?

That is not the hard way; it is the not-quite-as-easy way.
DataOutputStream wrapping ByteArrayOutputStream.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top