0

I'm new to C as a language, and I'm trying to do an XOR operation on two different data types, then store the result in a byte array at offset 1. The array is fixed, and will always be 8 bytes. I'd like to just check with all of you that I'm handling this correctly.

For background, I'd like buf to be the result as a uint8_t array, and my input data types are a char array and another byte array that will be constant in the application. I feel as though there's some casting that I'm missing, but I'm not sure where to look aside from asking:

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

int main()
{
    uint8_t HANDSHAKE_SN[8] = { 0x13, 0x81, 0x22, 0x13, 0xFA, 0x32, 0x65, 0xFA };
    uint8_t buf[8] = { 0x02, 0, 0, 0, 0, 0, 0, 0 };
    char sn[8] = "2345678";

    for(uint8_t i=1;i<9;i++)
    {
        buf[i] = sn[i-1] ^ HANDSHAKE_SN[i-1];
    }

    printf("%s",buf);
}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
  • 1
    Your code is definitely wrong. In the loop, you access `buf[i]` with i = 1 ... 8. So, the last iteration accesses `buf[8]`. Unfortunately, `buf` is declared as `uint8_t buf[8]` i.e. the last element is `buf[7]`. This is an out-of-bound access (a typical [off-by-one error](https://en.wikipedia.org/wiki/Off-by-one_error)) which introduces [U.B.](https://stackoverflow.com/a/4105123/1505939). – Scheff's Cat Jul 15 '19 at 05:16
  • Btw. if you are concerned to XOR `char` with `uint8_t`, you could simply cast `char` to `uint8_t`: `buf[i] = (uint8_t)sn[i-1] ^ HANDSHAKE_SN[i-1];`. However, in `printf("%s", buf);`, you pass a `uint8_t*` where `char*` is expected. This wouldn't me bother as much as the fact that `buf` might contain a non-0 terminated contents. The latter introduces [U.B.](https://stackoverflow.com/a/4105123/1505939) again. – Scheff's Cat Jul 15 '19 at 05:19

1 Answers1

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


#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))

#define TEST_SIZE (8)

int main()
{
    uint8_t HANDSHAKE_SN[TEST_SIZE] = { 0x13, 0x81, 0x22, 0x13, 0xFA, 0x32, 0x65, 0xFA };
    uint8_t buf[TEST_SIZE] = { 0 };
    char sn[TEST_SIZE + 1] = "12345678";

    for (uint8_t i = 0; i < ARRAY_LENGTH(buf); ++i)
    {
        buf[i] = sn[i] ^ HANDSHAKE_SN[i];
        printf("0x%hhx\n", buf[i]);
    }   
}
nivpeled
  • 1,810
  • 5
  • 17
  • Thanks for the help. Thanks for finding the U.B. error, I didn't even notice. One more thing, the goal was to have the assignment start at buf[1], since something needs to go in buf[0] later on. To your code, I feel like I should make the for loop size of sn and store the assignment at i+1? – Evan Johnson Jul 15 '19 at 13:45
  • 1
    simply have the for loop start from 1 and not 0: for (uint8_t i = 1; i < ARRAY_LENGTH(buf); ++i) – nivpeled Jul 15 '19 at 13:54