Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Casting woes...

0 views
Skip to first unread message

Thomas Zangl

unread,
Mar 10, 2010, 6:02:03 PM3/10/10
to
Hi!

For a project, I need to store some data generically in a uint8_t[].
The types are: uint8_t = unsigned integer 8bit, uint32_t = unsigned int
32 bit, uint64_t = unsigned integer 64bit.

I am using gcc 3.4.x on Debian and x86 platform.

The code is:

// ---------------------------------------------------------------------
{... some calculations going one ... }
uint32_t part_1=0;
uint64_t part_2=0;
uint8_t* result_ptr[12];

part_1=(.. some big number ..)
part_2=(.. another big number ..)

std::cout<<part_1<<"****"<<part_2<<std::endl;
// store the two numbers in result_ptr
memcpy(&result_ptr, reinterpret_cast<uint8_t*>(&part_1),4);
memcpy(&(result_ptr[4]), reinterpret_cast<uint8_t*>(&part_2),8);

{ .. result ptr is now left alone here .. }

uint32_t part_1_uint=0;
uint64_t part_2_uint=0;

//read the two number from result_ptr back into the uints
memcpy(&part_1_uint,result_ptr,4);
memcpy(&part_2_uint,&(result_ptr[4]),8);

// here, the output should be the same as above
std::cout<<part_1_uint<<"****"<<part_2_uint<<std::endl;

// ---------------------------------------------------------------------


The goal is, that I bascially want to store an uint32 and an uint64 in a
binary array (uint8). Later I want to restore the uint32 and the uint64
values. The first part, the uint32 is working fine. But the second
number, the uint64 is wrong.

Now my question is, what I am doing wrong? What I insert into the
result_ptr is not what I can read out of it. Seems I do something wrong
either while writing or reading or both.

Any hints please!

Thanks, Thomas

Thomas Zangl

unread,
Mar 10, 2010, 6:30:06 PM3/10/10
to
Am 11.03.2010 00:02, schrieb Thomas Zangl:

Hi!

Got the solution.

> std::cout<<part_1<<"****"<<part_2<<std::endl;
> // store the two numbers in result_ptr
> memcpy(&result_ptr, reinterpret_cast<uint8_t*>(&part_1),4);
> memcpy(&(result_ptr[4]), reinterpret_cast<uint8_t*>(&part_2),8);

Heres the bug:

memcpy(result_ptr, reinterpret_cast<uint8_t*>(&part_1),4);
memcpy((result_ptr[4]), reinterpret_cast<uint8_t*>(&part_2),8);

Pointing on a pointer does usually hurt ;-)

W/o the & its fine!

Yours, Tom

Pavel

unread,
Mar 10, 2010, 9:30:12 PM3/10/10
to
Hmm.. I am not sure you wrote what you wanted even though it may seem to
work. Here:

uint8_t* result_ptr[12];

You actually allocate 12 pointers, not 12 uint8_t. Is it what you want?
From your description, I would guess that:

uint8_t result_ptr[12];
..

memcpy(result_ptr, reinterpret_cast<uint8_t*>(&part_1),4);


memcpy(&(result_ptr[4]), reinterpret_cast<uint8_t*>(&part_2),8);

..

memcpy(&part_1_uint,result_ptr,4);
memcpy(&part_2_uint,&(result_ptr[4]),8);

should give you the desired result..

0 new messages