3

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;
    }
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
user3284506
  • 49
  • 1
  • 3

3 Answers3

3

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.

Community
  • 1
  • 1
Jimbo
  • 4,352
  • 3
  • 27
  • 44
  • 1
    This is almost right. You probably just want a single loop like this one. Just trying to follow the two-loop logic made my head hurt. That would not have been readable, maintainable code. This is very close to right. It has a bug in that it shifts after the or. It needs to do the shift before. Otherwise you're always going to have the 8 least significant bits at 0, and lose the top 8 most significant bits. : – m24p Feb 07 '14 at 16:02
  • Yep there's a bug... just verifying on ideone... fixed and thanks for pointing that out (+1)... quite embarrassed! – Jimbo Feb 07 '14 at 16:03
  • 1
    Minor: Suggest `PRIX64` to more easily match `paquet` to `input`. – chux - Reinstate Monica Feb 07 '14 at 17:25
2

Maybe this ?

uint64_t paquet = input[0]<<(8*7) | input[1]<<(8*6)
                                  | input[2]<<(8*5)
                                  | input[3]<<(8*4)
                                  | input[4]<<(8*3)
                                  | input[5]<<(8*2)
                                  | input[6]<<(8*1)
                                  | input[7];
n0p
  • 3,399
  • 2
  • 29
  • 50
2
char input[8] = "\x01\x23\x45\x67\x89\xAB\xCD\xEF";
uint64_t paquet = *(uint64_t*)"\x1\x0\x0\x0\x0\x0\x0\x0";

if(paquet == 1){
    //reverse
    char *f=&input[0], *b=&input[7];
    while(f<b){
        char tmp = *f;
        *f++ = *b;
        *b-- = tmp;
    }
}
paquet = *(uint64_t*)input;//memcpy(&paquet, input, sizeof(input));
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70