0

I have a char *key that represents hex values: "a35f64d2e1b5f5f" and I need to strore that in a u64 variable (64 bits). Since the char array is 16 bytes, I need to make so that the u64 variable stores each hex value into 4 bits. Therefore the whole variable will store (4 * 16) bits.

That was just an example of the values I could get, they can in fact be any 16 hex values. They specifically have to go into a u64 and I really don't know how to left shift only 4 bits at a time.

  • 1
    `char key[16]` can only hold 15 hex digits plus a null terminator when used as a string. – stark Sep 13 '21 at 16:56
  • @stark If it's not treated as a null terminated string it's fine though. `char key[16] = "aa35f64d2e1b5f5f"; // one char added to make it 16 chars` is fine in C. – Ted Lyngmo Sep 13 '21 at 17:19
  • 2
    The [`strtoull`](https://linux.die.net/man/3/strtoull) function ought to do the trick. – Steve Summit Sep 13 '21 at 17:25
  • 1
    @TedLyngmo Telling `strtoull()` where the end of the string is isn't what the endptr argument does. – Shawn Sep 13 '21 at 18:12
  • @Shawn Oh, misunderstanding on my part. I thought it was used both as an in and out parameter. Since that's not the case, _don't_ use `strtoull` with non null terminated strings at all :-) – Ted Lyngmo Sep 13 '21 at 18:14
  • strtoull works half of the time. Then it overflows into LLONG_MAX. How should I work around for those cases? – Alan Andrade Sep 13 '21 at 19:13
  • How many hex `char`s do you have in your `char[16]` array? If you have 16, you can't use `strtoull` (since it requires a null terminated string). – Ted Lyngmo Sep 13 '21 at 20:45
  • its a char[17] array. – Alan Andrade Sep 13 '21 at 21:44
  • @AlanAndrade "strtoull works half of the time. Then it overflows into LLONG_MAX." is suspicious. Did you mean `ULLONG_MAX`? – chux - Reinstate Monica Sep 13 '21 at 22:28
  • Yes, ULLONG_MAX – Alan Andrade Sep 13 '21 at 23:01
  • @AlanAndrade All arrays of 16 hex-digits convert to a `unsigned long long`. No overflow possible. – chux - Reinstate Monica Sep 14 '21 at 00:07
  • "`char *key` that represents hex values: "a35f64d2e1b5f5f" and I need to strore that in a u64 variable (64 bits). Since the char array is 16 bytes" is a contradiction. `key` is a _pointer_, not an array. Netiher `key` nor `"a35f64d2e1b5f5f"` are a _char array of 16 bytes_. Best to post code that demos your problem. – chux - Reinstate Monica Sep 14 '21 at 00:10
  • @AlanAndrade "_Since the char array is 16 bytes_" and "_its a char[17] array_" can't both be correct. Have you made sure that it's null terminated when you use `strtoull`? – Ted Lyngmo Sep 14 '21 at 17:27

0 Answers0