How I can translate a struct as hex/base16

I have the following sketch

typedef struct  {
  // Page that is transmitted
  unsigned int page;

  // Block that is transmitted
  unsigned int block;

  // A mumeric representation of the 32 byte segment that I send. 
  // I cannot send the page altogether, therefore a byte intexing is required
  uint8_t bytes_index;
  
  // Despite my buffer is 32 bytes the usable data may be less
  uint8_t length; 

  // Data buffer containing the data to be sent via serial
  byte data[BUFFER_LEN];
} usb_msg;

void setup() {
// SPI.begin();
 Serial.begin(9600);
 Serial.print(ACK);
}

void loop(){
  usb_msg msg;
  // Populate dummy data
  msg.page=1;
  msg.block=1;
  msg.bytes_index=2;
  msg.length = 10
  msg.data = [1,1,1,1,1,1,1,1,1,1];

  // Send it here
}

Is there a way to hex/base16 endode the msg before sending it through serial?

Serial.print(data_byte, HEX);

Leaves out leading zeros, and does not formatting symbols like "0x". Add those if you like.

Do you want the data sent as ASCII characters or as the raw binary data?

Do you want the data sent as ASCII characters or as the raw binary data?

As hex encoced ascii string.

void loop() {
  usb_msg msg = {1, 1, 2, 10, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
  // Populate dummy data
  //msg.page=1;
  //msg.block=1;
  //msg.bytes_index=2;
  //msg.length = 10;
  //msg.data = [1,1,1,1,1,1,1,1,1,1]; //this will not work

  // Send it here
  byte* ptr = (byte*)&msg;
  for (size_t i = 0; i < sizeof(usb_msg); i++){
    Serial.print(*ptr >>4, HEX);
    Serial.print(*ptr & 0x0F, HEX);
    ptr++;
  }
  delay(60000);
}

It worked but I want to understant more the rationale behind your code.

So far I understand that via:

  byte* ptr = (byte*)&msg;

You actually convert the struct as a byre array. Also I understand that each byte must be encoded one-by-one as hex.

But I cannot understand why at line:

    Serial.print(*ptr >>4, HEX);

You actually divide the byte value with 2^4 = 16

Also, what is the reason that you actually do a binary and with 0x0F as well at line:

    Serial.print(*ptr & 0x0F, HEX);

Do you actually try to encode the first half (first 4 bits) and the latter half (other 2 bitsd) of the byte seperately, if yes why?
If yes why

Yes, The first line sends the upper 4 bits as a hex character, the 2nd line sends the lower 4 bits as a hex character. If you just print(*ptr, HEX) there will be no leading zero for numbers less than 0x10. As an example 0x01 0x01 would print as "11" instead of "0101".

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.