# Converting a string to a number, string can be a HEX, BIN or DEC value

Hi,

The problem I'm facing is that the user has to input a value trough the serial monitor.
This would be easy if it were only a decimal number they may input.
But they can use a HEX, BIN or DEC value as input.
They would be defined by the commonly used 0x for hex, 0b for bin and nothing for decimal.
After a lot of attempts I came here to ask for some advice, the code you find under here is one of the many attempts (that obviously failed).

Thank you in advanced for helping me.
~TJHUNTER

``````      if(data.charAt(0) == ("0")) {
if(data.charAt(1) == ('b')) {
data.remove(0, 2);
I2C_data[n] = (byte) strtol(data, NULL, 2);
}
else if(data.charAt(1) == ('x')) {
data.remove(0, 2);
I2C_data[n] = (byte) strtol(data, NULL, 16);
}
}
else {
I2C_data[n] = (byte) data.toInt();
}
``````

strtol() handles decimal, hex, and octal, for binary you have to help it a bit.

``````long getValue(const char* from) {
long value = 0;
Serial.print(F("conversion of '"));
Serial.print(from);
Serial.print(F("' gives "));
if (from == '0' && (from == 'b' || from == 'B')) {
value = strtol(from + 2, nullptr, 2);
} else {
value = strtol(from, nullptr, 0);
}
Serial.println(value);
return value;
}
void setup() {
Serial.begin(250000);
getValue("129");
getValue("0x81");
getValue("0201");
getValue("0b10000001");
}
void loop() {}
``````
``````conversion of '129' gives 129
conversion of '0x81' gives 129
conversion of '0201' gives 129
conversion of '0b10000001' gives 129
``````

Thank you!
This fixed everything.