2015-08-07 4 views
0

Я хочу написать целое число в двоичном файле с Java (Android), а затем прочитать его с кодом на C++. Мой кода в Java является:Запись int в двоичный буфер (Android) и чтение с C++

byte [] mybuffer = ByteBuffer.allocateDirect(4).putInt(1000).array; 
out.write(mybuffer, 0, 4); // out is FileOutputStream 

Читателя в C++

std::ifstream fileToRead; 
fileToRead.open("myFile", std::ios::binary); 
if (!fileToRead.is_open()){ 
    std::cout << "[ERROR] Can't open file" << std::endl; 
    exit(-1); 
} 
int * myInt = new int; 
fileToRead.read((char*)&myInt[0], 4); 
std::cout << " The integer is " << myInt[0] << std::endl; 

Но я получаю значение, которые не делают чувство.

Благодаря

выход Java:

buffer[0] = 0 
buffer[1] = 0 
buffer[2] = 3 
buffer[3] = -24 

выход C++:

The integer is -402456576 
+0

Вы должны добавить свои странные выходы на свой вопрос :) (также нет актуального «вопроса» в вашем вопросе) – m02ph3u5

+1

Фактическая часть чтения кода C++ выглядит законной, но она, безусловно, получила представление о Java-кодере. Нет необходимости динамически выделять эту переменную 'myInt', достаточно указать адрес-оператора' & ': int myInt; fileToRead.read (reinterpret_cast (& myInt), sizeof (myInt)); ' –

+0

Было бы полезно увидеть примеры ввода и вывода, особенно напечатанные побайтно. – shakurov

ответ

3

Вы можете столкнуться с проблемой порядка байтов:

#include <cstdint> 
#include <fstream> 
#include <iostream> 
// For ntohl with Linux (Windows has similar): 
#include <arpa/inet.h> 

int main() 
{ 
    // You can use the constructor to open the file: 
    std::ifstream fileToRead("myFile", std::ios::binary); 
    // Just check the general state of the stream: 
    if(!fileToRead){ 
     std::cout << "[ERROR] Can't open file" << std::endl; 
     // Please do not use exit to terminate a program: 
     return -1; 
    } 
    // No need to allocate an integer. Also be specific about the size: 
    int32_t myInt; 
    // There might be byte order issues, here (Java is big-endian): 
    fileToRead.read((char*)&myInt, sizeof(int32_t)); 
    // To fix it convert the integer from network byte order to host byte order: 
    myInt = ntohl(myInt); 
    std::cout << " The integer is " << myInt << std::endl; 
} 
+0

Да это работает спасибо! Будет ли этот метод работать с большим массивом float? Спасибо – Snoopyjackson

0

Для хорошего порядка, а java использует по умолчанию BIG_ENDI AN байт:

byte[] mybuffer = ByteBuffer.allocateDirect(4) 
        .order(Order.LITTLE_ENDIAN).putInt(1000).array(); 

Это заказ на архитектуру памяти процессора Intel.