1

I'm trying to convert latitude and longitude to a byte arrayusing Java and then convert the byte array to double using C++. SO far, here's what I'm doing:

I have a byte array of {0x40,0x4a, 0x62, 0x65, 0x27, 0xa2, 0x05, 0x79} which gives 52.768712 in JAVA.

I'm trying to do the same thing in C++ using:

unsigned char data[8] = { 0x40,0x4a, 0x62, 0x65, 0x27, 0xa2, 0x05, 0x79};

 double sample;
 double conversion;

 copy(data, data+ sizeof(double), reinterpret_cast<char*>(&sample));
 memcpy(&conversion, data, sizeof(double));

 cout <<fixed << sample << endl;
 cout <<fixed << conversion << endl;

But this outputs

93624845218206212768416858147698568034806357864636725490778543828533000856049725637297881892477906693728822997596617150540736669122257619339758101303551253860040255473731364930515446918886205365571056786975140751691636070476504921373224351498841838203471739594278994672877568.000000

What am I doing wrong here?

0

1 Answer 1

1

Endianness. Java is big-endian, while C++ is platform dependent.

This works for me on an Intel-based Windows PC (little-endian):

#include <iostream>
#include <cstring>
#include <algorithm>

int main()
{
    unsigned char data[8] = { 0x40,0x4a, 0x62, 0x65, 0x27, 0xa2, 0x05, 0x79};

     double sample;
     double conversion;

     std::reverse(std::begin(data), std::end(data)); // Reverse byte order here
     std::copy(data, data+ sizeof(double), reinterpret_cast<char*>(&sample));
     std::memcpy(&conversion, data, sizeof(double));

     std::cout << std::fixed << sample << std::endl;
     std::cout << std::fixed << conversion << std::endl;
}

Output:

52.768712
52.768712

Note that this is inherently non-portable, since endianness, size of double, and floating point representation are not defined by the C++ language standard.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.