HUGE JAVA/C++ PROBLEM!

Started by
22 comments, last by Enigma 18 years, 6 months ago
Read one byte at a time, store them in b1, b2, b3, and b4

You can build your number from the bytes like this:

int x = 0;
x |= b1 <
Advertisement
Err my post got messed up, I'll try that again...

Read one byte at a time, store them in b1, b2, b3, and b4

You can build your number from the bytes like this:

int x = 0;
x |= b1 << 24;
x |= b2 << 16;
x |= b3 << 8;
x |= b4;
It would be better to write your own macros or inline functions, like these (which should work both in Java and C++):

inline int swap_bytes(int n){  // For better performance, you can drop the first and last & operation  // For better readability, it's nice to leave them there  return ((n >> 24) & 0x000000FF) |         ((n >> 08) & 0x0000FF00) |         ((n << 08) & 0x00FF0000) |         ((n << 24) & 0xFF000000);}inline short swap_bytes(short n){  return ((n >> 08) & 0x00FF) |         ((n << 08) & 0xFF00);         }


EDIT: This solution should be faster than reading 1 byte at a time, but you said performance is not an issue, so either method should work fine.
I love you Anonmyous Mystery man and s_p_oniel thanks for the help
any ideas on how to right the integer form of that fuction to work with floats?
Why not try formating the file in ASCII? So if you want to have an integer at the start, then save it as a ASCII number. Then when loading the file in C++ use the std::atoi function in <cstring> to make the ASCII character into an integer.
I could really use some help in figuring out how I could swap the bytes to reconstruct a float
I suggest you use an ASCII file.

However, if you insist...

the root cause of the problem is that Java uses a different endian-ness then x86. x86 is little endian; Java (apparently) is big endian. Therefore, you must always flip the order of bytes for everything you read in, including floats.

Just read in the bytes, flip the order, and cast to a float.

Note that this does not necessarily always work. You are relying on the tenaious fact that Java and C++ happen to use the same size and representation for a float. Seriously, just use an ASCII file format.
The alternative portable way of doing it is to read the Java representation into a set of bytes, extract the mantissa, exponent and sign and reconstruct using the ldexp() function. You'll have to handle special cases like NAN and infinity yourself though.
Ok but can anyone give me a working example on how to reconstruct a float with 4 bytes?, because it isnt as easy as the interger when I tried it.

This topic is closed to new replies.

Advertisement