#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int hex_char_to_int(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1; // Erro!
}
float hex_string_to_little_endian_float(const char* hex_string) {
size_t len = strlen(hex_string);
if (len != 8) { // Float são 4 bytes, isto é, 8 dígitos hexa
Serial.println("Erro: A string hexadecimal deve conter 8 dígitos.\n");
return 0.0f; //
}
uint32_t raw_value = 0;
for (int i = 0; i < 4; ++i) {
// Obter 2 caracteres hexa para cada byte.
int high_nibble = hex_char_to_int(hex_string[i * 2]);
int low_nibble = hex_char_to_int(hex_string[i * 2 + 1]);
if (high_nibble == -1 || low_nibble == -1) {
Serial.println("Erro: Não é um dígito hexadecimal válido.\n");
return 0.0f;
}
uint8_t byte = (uint8_t)((high_nibble << 4) | low_nibble);
// Para o formato little-endian, bytes são lidos da ordem inversa
// O primeiro byte da string é o byte menos significativo no float
raw_value |= ((uint32_t)byte << (i * 8));
}
union {
uint32_t i;
float f;
} converter;
converter.i = raw_value;
return converter.f;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
const char* hex_str = "cdccc841"; // Dec: 25,1 -> Hex:41-c8-cc-cd
float result = hex_string_to_little_endian_float(hex_str);
Serial.print("Hex string: ");
Serial.print(hex_str);
Serial.print(", float: ");
Serial.println(result);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}