Hello,
My Arduino program involves SHA256 hashing, using this cryptography library https://rweather.github.io/arduinolibs/crypto.html
For that purpose I'm using some strings of hex characters. A simple version of my program is as follows:
My program works fine, however I need to store many hash values that change dynamically, and the Dynamic memory gets depleted and the program misbehaves. So I was thinking to store them as bytes to save memory.
For that purpose I need two functions, hex2string() and string2hex(). I've tried some solutions found in this forum but didn't work for me. Can someone help?
Thanks!
In a common EEPROM memory (which has a limited amount of writing, and long writing time) or something faster, perhaps as a FRAM (similar to EEPROM but much faster and with a much higher rewrite limit as well)
For that purpose I need two functions, hex2string() and string2hex(). I've tried some solutions found in this forum but didn't work for me. Can someone help?
Post what you tried.
hex2string() Is pretty easy, you iterate over your byte array and for each byte B
you take the high 4 bits (shift right >> by 4 position) byte h = B >> 4;
you take the low 4 bits (masking with & 0x0F) byte l = B & 0x0F;
In both cases test if those 4 bits (h and then l) are strictly less than 10, then your ASCII char is ‘0’+h (or ’0’+l) and if greater than 10, then you ASCII char is ’A’+h-10 (or ’A’+l-10) then you just add those chars into your buffer starting with the high one
If your byte array is N byte long, your cString buffer will need to be 2N+1 bytes long (don’t forget the trailing NULL char ‘\0’)
Going the other way is somewhat similar, you need to read ASCII chars in pairs. Say your cString is in char hexString[2*N+1]; then read by groups of 2 (a for loop with index going up by 2) chars at index and index+1:
for (byte i=0; i<2*N; i+=2) {
char h = hexString[i];
char l = hexString[i+1];
byte value = ...;
}
To find the value it’s the reverse operation than before. If your char (h or l) is between ‘0’ and ‘9’, then use h-‘0’ as high part value (HV) (same for low), and if your char is between ‘A’ and ‘F’ use h-‘A’+10 (same for low) as low part value (LV). Your final byte is 16*HV+LV or if you want to play with bits (HV<<4) | LV