fork(1) download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4.  
  5. // Function to copy data from a const char* to a uint8_t* buffer
  6. // buff[0] = data_length, buff[1..length] = actual data
  7. void copy_data_to_buffer(const char *data, uint8_t *buff, size_t buff_size) {
  8. // Calculate the length of the input data
  9. size_t data_length = strlen(data);
  10.  
  11. // Ensure the buffer is large enough to hold the length byte + data + null terminator (if needed)
  12. if (data_length + 1 > buff_size) {
  13. printf("Error: Buffer is too small to hold the data and length.\n");
  14. return;
  15. }
  16.  
  17. // Store the length in buff[0]
  18. buff[0] = (uint8_t)data_length;
  19.  
  20. // Copy the data into buff[1..length]
  21. memcpy(&buff[1], data, data_length);
  22.  
  23. // Optionally, null-terminate the buffer (if needed)
  24. buff[5 + 1] = '\0';
  25. }
  26.  
  27. int main() {
  28. const char *data = "Hello"; // Example input data
  29. uint8_t buff[6]; // Buffer to hold the length and data
  30.  
  31. // Copy the data into the buffer
  32. copy_data_to_buffer(data, buff, sizeof(buff));
  33.  
  34. // Print the length and copied data
  35. printf("sizeof(buff)=%d\n",sizeof(data));
  36. printf("Data length: %d\n", buff[6]);
  37. printf("Copied data: %s\n", (char *)&buff[1]);
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
sizeof(buff)=8
Data length: 0
Copied data: Hello