Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char[] to uint64_t

Tags:

c

char

binary

I'm trying to convert an array of char into a uint64_t but it doesn't work. Here's my code :

char input[8];
//Initialisation of input
int i,j;
uint64_t paquet=0;
for(i = 0; i < 8; i++)
{
    for(j = 0; j < 8; j++)
    {
        paquet+= (input[i] >> j) & 0x01;
        paquet = paquet << 1;
    }
}
like image 789
user3284506 Avatar asked Dec 06 '25 17:12

user3284506


1 Answers

Assuming that the input buffer has stored the data in a little endian representation, which means that the least significant byte is at the lowest address and the most significant byte at the highest address then you can do something like the following.

#include <stdio.h>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

int main(void) 
{
    int i;
    unsigned char input[8] = {0x01, 0x02, 0x03, 0x04, 0x5, 0x06, 0x07, 0x08 };
    uint64_t paquet = 0;
    for( i = 7; i >= 0; --i )
    {
        paquet <<= 8;
        paquet |= (uint64_t)input[i];
    }

    printf("0x%" PRIx64 "\n", paquet);

    return 0;
}

You can see the working example on ideone.

If the buffer is stored in big endian mode then reverse the loop.

Thank you to m24p for pointing out a bug in my initial draft.

like image 194
Jimbo Avatar answered Dec 10 '25 02:12

Jimbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!