Pararera
Pararera

Reputation: 372

Getting weird numbers from array pointer

I made function that splits given values(from array pointer) into bytes. For simplicity I use one byte values. Why I'm getting weird numbers when I print values?

void writePage(uint16_t address, uint64_t *data, uint8_t const len, uint8_t const bPD)
{
    uint8_t pageBuffer[32];
    uint8_t bytes2Write = len * bPD;

    for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
    {
        std::cout << int(dataIndex) << std::endl;
        std::cout << data[dataIndex] << std::endl;
        for (uint8_t i = 0; i < bPD; i++)
        {
            pageBuffer[i + (dataIndex * bPD)] = ((data[dataIndex] >> 8 * i) & 0xFF);
            std::cout << int(pageBuffer[i + (dataIndex * bPD)]) << std::endl << std::endl;
        }
    }
}

int main()
{
    uint8_t array[3] = { 255, 20, 30 };
    std::cout << int(array[0]) << int(array[1]) << int(array[2]) << std::endl;
    writePage(0, (uint64_t*)array, 3, 1);

    getch();
    return 0;
}

Output

2552030

0

119944479905023

255

1

70453687222272

0 2

0

0

Upvotes: 0

Views: 111

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

If your goal is to take any type,and to break up the bytes, the way it is almost always done is to cast a pointer to that type to a char * and work with the char *.

Here is an example using a stripped down version of your code.

#include <iostream>

struct foo
{
    int x;
    double y;
    char z;
};

void writePage(uint16_t address, char *data, uint8_t const len)
{
    for (uint8_t dataIndex = 0; dataIndex < len; dataIndex++)
    {
        std::cout << (int)data[dataIndex] << std::endl;
    }
}

int main()
{
    uint8_t array[3] = { 255, 20, 30 };
    std::cout << int(array[0]) << " " << int(array[1]) << " " << int(array[2]) << std::endl;
    writePage(0, reinterpret_cast<char *>(&array[0]), sizeof(array));
    foo f;
    f.x = 10;
    f.y = 20;
    f.z = 'g';
    std::cout << "Here are the bytes of foo, which has a sizeof(foo) as " << sizeof(foo) << "\n" ;
    writePage(0, reinterpret_cast<char *>(&f), sizeof(f));
    return 0;
}

Output:

255 20 30
-1
20
30
Here are the bytes of foo, which has a sizeof(foo) as 24
10
0
0
0
0
0
0
0
0
0
0
0
0
0
52
64
103
-54
-117
-54
-2
127
0
0

Upvotes: 1

Related Questions