Extract from array to integer

83 Views Asked by At

How to extract the number 0145525000 from the array 0x00, 0x50, 0x52, 0x45, 0x01 in C language?

#include <stdio.h>

int main()
   {
    uint8_t arr[] = {0x00, 0x50, 0x52, 0x45, 0x01};
    uint32_t number = 0;

    // Sorry i dont know how to solve this

    printf("Number: %d\n", number);

    return 0;
   }

It is necessary to convert from the last element to zero into one unsigned integer?

1

There are 1 best solutions below

1
Vlad from Moscow On

The hexadecimal constant 0145525000 that will be more correctly to write like 0x0145525000 contains at least 9 hexadecimal digits (if to ignore the leading 0) that can not be represented in an object of the type uint32_t. The variable number should be declared as having type uint64_t.

Now what you need is to write a loop that will store hexadecimal values present in the array arr in the reverse order to the variable number.

Here you are.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main( void )
{
    uint8_t arr[] = { 0x00, 0x50, 0x52, 0x45, 0x01 };
    const size_t N = sizeof( arr ) / sizeof( *arr );
    uint64_t number = 0;

    for (size_t i = N; i != 0; )
    {
        number = 0x100 * number + arr[--i];
    }

    printf( "%010" PRIx64 "\n", number );
}

The program output is

0145525000

The statement within the for loop

number = 0x100 * number + arr[--i];

may be rewriten also like

number = ( number << 8 ) + arr[--i];