matthijskooijman / arduino-lmic

:warning: This library is deprecated, see the README for alternatives.
706 stars 649 forks source link

Byte Swap Function #149

Open trlafleur opened 6 years ago

trlafleur commented 6 years ago

This is a function I use to do a byte swap. This allow the TTN keys to be used and displayed in correct order... The program will do the byte swap prior to sending them on to TTN.

// **********************************************************
// Function to do a byte swap in a byte array
void RevBytes(unsigned char* b, size_t c)
{
  u1_t i;
  for (i = 0; i < c / 2; i++)
  {
    unsigned char t = b[i];
    b[i] = b[c - 1 - i];
    b[c - 1 - i] = t;
  }
  if (c & 1)
    b[c / 2] = b[c / 2];
}

// Example...

/* ************************************************************************************** */
// LoRaWAN DevEUI, unique device ID (LSBF)
//static const u1_t DEVEUI[8]  = { 0x07, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  static const u1_t DEVEUI[8]  = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x07 };
/* ************************************************************************************** */

//* ************************************************************************************** */
// provide device ID (8 bytes, LSBF)
void os_getDevEui (u1_t* buf) {
    memcpy(buf, DEVEUI, 8);
    RevBytes(buf, 8);      // TTN requires it in LSB First order, so lets swap byte's
}
matthijskooijman commented 6 years ago

I would really like to do something like this at compiletime, ideally starting with a 64-bit integer instead of separate bytes. In C++ it would be possible with some constexpr magic, but in plain C I guess a preprocessor macro could do the trick. I haven't found the time to write one yet, though.

cyberman54 commented 6 years ago

Using a pointer makes things easier:

// Print a key on display

void DisplayKey(const uint8_t * key, uint8_t len, bool lsb) {

  uint8_t start=lsb?len:0;

  uint8_t end = lsb?0:len;

  const uint8_t * p ;

  for (uint8_t i=0; i<len ; i++) {

    p = lsb ? key+len-i-1 : key+i;

    u8x8.printf("%02X", *p);

  }

  u8x8.printf("\n");

}

jcwren commented 6 years ago

What is the point of this statement? If c is an odd number, you're assigning a byte to itself.

if (c & 1)
  b[c / 2] = b[c / 2];
trlafleur commented 6 years ago

Sorry about that extra code, it was reminisce from another version that also did nibble swap... so it can be removed.... As you can see, it uses very little code...

Amount of program storage used:
ESP32         68bytes
ARM M0        56bytes
ATMega 1284   74bytes

// **********************************************************
// Function to do a byte swap in a byte array
void RevBytes(unsigned char* b, size_t c)
{
  u1_t i;
  for (i = 0; i < c / 2; i++)
  {
    unsigned char t = b[i];
    b[i] = b[c - 1 - i];
    b[c - 1 - i] = t;
  }
}