void setup() {
// Start the serial communication
Serial.begin(9600);
const char *str = "16385";
// Example const char* to be converted
unsigned char ptr[256];
memset(ptr,0,256);
int inc = 0;
ptr[inc] = 0x02;
inc++;
// val_offset++;
long numb = atoi(str);
int bits = 0;
int data_len = 0;
if(numb >= 128)
{
long numbs = numb;
while (numbs > 0) {
bits++;
numbs >>= 1; // Right shift the number by 1
}
data_len = bits/7; //2
if(bits%7)
data_len++; //3
ptr[inc] = data_len;
// inc++;
// val_offset++;
inc += data_len;
for(int iii = 0; iii<data_len; iii++) //
{
ptr[inc - iii] = numb >> (7*iii) & 0x7F;
if(iii != 0)
ptr[inc - iii] |= 0x80;
// val_offset++;
}
inc++;
}else{
ptr[inc] = 0x01;
inc++;
// val_offset++;
ptr[inc] = numb & 0x7F;
inc++;
// val_offset++;
}
int ptr_total_len = inc;
Serial.print("[DEBUG] packet: ");
for (int i = 0; i < ptr_total_len; i++)
{
inc = i;
// sprintf( "%X", (const char*)ptr[inc]);
char hexString[3];
byteToHex(ptr[inc], hexString);
Serial.print(hexString);
Serial.print(" ");
}
Serial.println();
}
void loop() {
// Do nothing here
delay(10);
}
void byteToHex(unsigned char byteValue, char* hexString) {
const char hexDigits[] = "0123456789ABCDEF";
hexString[0] = hexDigits[(byteValue >> 4) & 0x0F];
hexString[1] = hexDigits[byteValue & 0x0F];
hexString[2] = '\0'; // Null-terminate the string
}