Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ double to byte array

Tags:

c++

arrays

byte

I want to cast double numbers to byte array (unsigned char*)

std::vector<unsigned char*> v;

    for (int i = 0; i < 5; i++)
    {

        double a = 3.14+i;
        double b = 4.44+i;

        v.push_back((unsigned char*)&a);
        v.push_back((unsigned char*)&b);
    }

    for (int i = 0; i < v.size(); i++)
        std::cout << *((double*)v.at(i)) << std::endl;

i've done this, but it always gives me last set of numbers.

current output:

7.14
8.44
7.14
8.44
7.14
8.44
7.14
8.44
7.14
8.44

How it is supposed to be:

3.14
4.44
4.14
5.44
5.14
6.44
6.14
7.44
7.14
8.44
like image 738
BojanGolob Avatar asked Apr 30 '26 20:04

BojanGolob


2 Answers

std::vector<unsigned char*> is a vector (list) of pointers to unsigned char. This is not what you want.

I guess you want to have std::vector<unsigned char> (no pointers here).

For each number you want to add to the list, you have to add several (typically 8) bytes to it. In order to do it, the simplest method is:

const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&a);
for (size_t i = 0; i < sizeof(double); ++i)
    v.push_back(ptr[i]);

To extract a number from such an array of bytes:

for (int i = 0; i < v.size(); i++) {
    double number;
    memcpy(&number, &v.at(i * sizeof(double)), sizeof(double));
    std::cout << number << std::endl;
}
like image 138
anatolyg Avatar answered May 03 '26 11:05

anatolyg


This is really wrong you are saving pointers to address that would be out of scope (a and b), this would cause invalid memory access (would work as you expected OR would not).

You are declaring a vector of pointer (std::vector<unsigned char*>) not a vector of unsigned char (std::vector<unsigned char>).

According to the output of this sample, it appear as if GCC (version 4.9.0) it reusing the same memory for variables a and b in the loop OR extracted away the variables of the loop. Because it prints only two different address of the pointer storage in the vector.

#include <vector>
#include <iostream>

int main() {
    std::vector<unsigned char*> v;

    for (int i = 0; i < 5; i++) {

        double a = 3.14 + i;
        double b = 4.44 + i;

        v.push_back((unsigned char*)&a);
        v.push_back((unsigned char*)&b);
    }

    for (int i = 0; i < v.size(); i++) {
        std::cout << std::hex << ((double*)v.at(i)) << std::dec << std::endl;
        std::cout << *((double*)v.at(i)) << std::endl;
    }
}

Output:

0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
0x22fec0  -> Address 1
7.14
0x22fec8  -> Address 2
8.44
like image 35
NetVipeC Avatar answered May 03 '26 09:05

NetVipeC