tags:

views:

76

answers:

1

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.

+2  A: 
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 ));
    }
}
Nikolai N Fetissov
Note that the data in ptr will only be little-endian on little-endian machines: This solution will result in big-endian output on big-endian machines, and little-endian output on little endian machines. Understand what endian-ness means, and if endian-ness matters, seek a more robust solution.
Thanatos
Thanks for your solution,I hope it work,but would u help me,how I can count how many byte is it? in other hand for example 10 equal 1001 so it is 4 byte
rima
You can deal with freaky sizes of `char` by replacing `j << 3` with `j * CHAR_BIT`, and `0xff` with `((1 << CHAR_BIT) - 1)`. You'll need to include `<climits>` for that.
Mike Seymour
Thanks Mike, I knew I was forgetting something.
Nikolai N Fetissov
@rima, I think we are still lost at what you need to do. Is it a single `long` number or an array of `long`s? Can you include at least some snippet of code in the question of what you think you should be doing?
Nikolai N Fetissov
I try to change some codes,emmm it's hard for me to put codes here,It was code of one of the WSN security algorithm (ECC)...
rima
Prefer `j * 8` over `j << 3` - the former is much clearer, and is what you are actually doing. Leave the micro-optimization to the compiler.
Thanatos