I want to create a file containing exactly 8 bytes representing an unsigned long number. The file is created using Java and then read by C ++. So Java creates a file:
import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; public class Writer { public static void main(String[] args) throws Exception { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(12345); ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write(buffer.array()); try (FileOutputStream outputStream = new FileOutputStream("myFile")) { outputStream.write(stream.toByteArray()); } } }
And here is how C ++ reads:
#include <iostream> #include <vector> #include <fstream> #include <stdio.h> using namespace std; // I use this to get each byte from a file static std::vector<char> ReadAllBytes(char const* filename) { std::ifstream ifs(filename, ios::binary|ios::ate); std::ifstream::pos_type pos = ifs.tellg(); std::vector<char> result(pos); ifs.seekg(0, ios::beg); ifs.read(&result[0], pos); return result; } int main (int argc, char* argv[]) { std::vector<char> bytes = ReadAllBytes("myFile"); std::vector<char>::iterator it = bytes.begin(); char longBytes[8]; std::copy(&(*it), &(*it) + 8, longBytes); unsigned long value = *((unsigned long*)longBytes); std::cout << "Size: " << value; }
The expected output is 12345 , but instead I get 4120793659044003840 .
I'm not sure if I did it wrong in Java or C ++. Or both. What was I supposed to do?
java c ++ long-integer
Voldemort
source share