Amir
Amir

Reputation: 1979

How do I convert an unsigned long array to byte in C++?

How do I convert an unsigned long array to byte in C++? I'm developing using VS2008 C++.

Edit:

I need to evaluate the size of this converted number,I want to divide this long array to a 29byte array.
for example we have long array = 12345;
it should convert to byte and then I need its length to divide to 29 and see how many packet is it.

losing data is important but right now I just want to get result.

Upvotes: 1

Views: 1488

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84239

long array[SOME_SIZE];
char* ptr = reinterpret_cast<char*>( array ); // or just ( char* )array; in C

// PC is little-endian platform
for ( size_t i = 0; i < SOME_SIZE*sizeof( long ); i++ )
{
    printf( "%x", ptr[i] );
}

Here's more robust solution for you, no endianness (this does not cover weird DSP devices where char can be 32-bit entity, those are special):

long array[SOME_SIZE];

for ( size_t i = 0; i < SOME_SIZE; i++ )
{
    for ( size_t j = 0; j < sizeof( long ); j++ )
    {
        // my characters are 8 bit
        printf( "%x", (( array[i] >> ( j << 3 )) & 0xff ));
    }
}

Upvotes: 2

Related Questions