0

I am currently sending an array of unsigned, 8 bit integers to a C program through Bluetooth (as a characteristic). When this packet is received, I want to take a pair of the indexes and "concatenate" their numbers, like so:

Input: [0xDE, 0xAD, 
        0xDE, 0xAD, 
        0xBE, 0xEF]

Output: [0xDEAD, 0xDEAD, 0xBEEF]

However, I am running into a strange issue. My code works fine when I output to an even index (Taking the first two elements of the array and concatinating them), but fails when I output to an odd element (For example, trying to concatinate elements 3 and 4 (0xDE and 0xAD).

So, my output that I am getting from the program is this:

Input: [0xDE, 0xAD, 
        0xDE, 0xAD, 
        0xBE, 0xEF]

Output: [0xDEAD, 0xADDE, 0xBEEF]

Here is my code:

  for(int i = 0; i < numUUID; i++)
  {
      // The i+1 and i+2 are because the first value of the array contains
      // a byte on how many UUIDs are incoming
      uuidFilter[i] = (incoming[i + 1] << 8) | incoming[i + 2];
  }
Ryan Moeller
  • 151
  • 2
  • 11

2 Answers2

4

Assuming your input is like this:

[numUUID, 0xDE, 0xAD, 0xDE, 0xAD, 0xBE, 0xEF]

your high bytes are at indices 1, 3, and 5 while low bytes are at indices 2, 4, and 6. Notice that they go by twos. That means that when you index into the array you should have a 2*i somewhere, so that you step by two on each increment. Here's the answer:

for(int i = 0; i < numUUID; i++)
{
    uuidFilter[i] = (incoming[2*i + 1] << 8) | incoming[2*i + 2];
}

This is assuming that numUUID is the number of pairs that you are concatenating. If it's the number of bytes, then of course you need to divide that by two in the loop condition.

Max
  • 21,123
  • 5
  • 49
  • 71
  • OP didn't make it clear what `numUUID` meant. I added my assumption to my answer. – Max Jul 19 '18 at 20:39
1

You're processing 2 elements from the incoming array but only incrementing i by 1. So you're processing
incoming[i_1] and incoming[i_2]
incoming[i_2] and incoming[i_3]

but it looks like you should be incrementing i by 2 which would give you
incoming[i_1] and incoming[i_2]
incoming[i_3] and incoming[i_4]

You'd also have to start your loop at i=1 to skip the first byte.

Bobby Tables
  • 191
  • 2
  • 15