# Convert hex string to int

**URL:** <https://forum.arduino.cc/t/convert-hex-string-to-int/301014>\
**Category:** Programming\
**Created:** [March 28, 2015, 8:56pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014 "2015-03-28T20:56:39Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![giantsquid](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@giantsquid](https://forum.arduino.cc/u/giantsquid)\
**Post date:** [March 28, 2015, 8:56pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/1 "2015-03-28T20:56:39Z")

</div>

I apologize if this is a novice question, but I've been googling for a while now and couldn't find a solution. I have a string, string bs02 that outputs a 2 char hex piece from "00" to "FF". My ultimate goal is turning this string into an integer. Could anyone give me some code that can do that? Would i have to convert the string bs02 to hex first and then convert it to int or is already understood to be hex and just needs to be converted from hex to int?  
thanks again for your time!

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [March 28, 2015, 10:41pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/2 "2015-03-28T22:41:07Z")

</div>

Is the hex in a string (null terminated char array) or a String (object created using the String library) ?

---

<div class="post-metadata">

**Author:** ![guix](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/guix/32/215371_2.png) [@guix](https://forum.arduino.cc/u/guix)\
**Post date:** [March 29, 2015, 1:18am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/3 "2015-03-29T01:18:51Z")

</div>

You don't have to convert the string to hex, because it's not possible 😛 A number can be written in few different way (decimal, binary, hex..) but the difference is only visual.

All these are exactly the same thing once compiled:

```plaintext
byte b = 255;
byte b = 0b11111111;
byte b = 0xFF;

```

To convert a hex string to int, you can use function [strtol](http://www.cplusplus.com/reference/cstdlib/strtol/) ( or [strtoul](http://www.cplusplus.com/reference/cstdlib/strtoul/) if you want a unsigned result). Alternatively (because I like and use this function a lot), [sscanf](http://www.cplusplus.com/reference/cstdio/sscanf/) .

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1290082_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [March 29, 2015, 1:25am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/4 "2015-03-29T01:25:45Z")

</div>

If it is truly a 2 char array that holds the hex string, then try this:

```cpp
void setup() {
  Serial.begin(9600);
}

void loop() {
  char input[3];
  int charsRead;
  int val;
  
  if (Serial.available() > 0) {
    charsRead = Serial.readBytesUntil('\n', input, 2);  // fetch the two characters
    input[charsRead] = '\0';                            // Make it a string

    val = StrToHex(input);                              // Convert it

    Serial.print("Hex input was: ");                    // Show it...
    Serial.print(input);
    Serial.print("  decimal = ");
    Serial.println(val);
  }
}

int StrToHex(char str[])
{
  return (int) strtol(str, 0, 16);
}

```

I'm not a big fan of _sscanf()_ because it eats more memory than is usually necessary.

---

<div class="post-metadata">

**Author:** ![guix](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/guix/32/215371_2.png) [@guix](https://forum.arduino.cc/u/guix)\
**Post date:** [March 29, 2015, 1:38am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/5 "2015-03-29T01:38:31Z")

</div>

> econjack:  
> I'm not a big fan of _sscanf()_ because it eats more memory than is usually necessary.

How much functions can sscanf replace? I haven't tested but I think that if in your code you use many atoi, strtol, strtod, strcat, and more... possibly strtok, etc... Then it might be worth replacing all those with sscanf, maybe it will use less memory then 😛

Edit: not strcat, that's a replacement job for sprintf 😛

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1290082_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [March 29, 2015, 1:48am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/6 "2015-03-29T01:48:58Z")

</div>

> How much functions can sscanf replace? I haven't tested but I think that if in your code you use many atoi, strtol, strtod, strcat, and more... possibly strtok, etc... Then it might be worth replacing all those with sscanf, maybe it will use less memory then

True, but how many programs need _atoi(), strtol(), strcat(),_ and all of the other features built into _sscanf()_ in the same program? If you need all of those tools, then it might save some memory. Still, if the only tool you have is a hammer, pretty soon all your problems start to look like a nail.

---

<div class="post-metadata">

**Author:** ![giantsquid](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@giantsquid](https://forum.arduino.cc/u/giantsquid)\
**Post date:** [March 29, 2015, 5:38am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/7 "2015-03-29T05:38:44Z")

</div>

@UKhelibob the hex isn't in a char array, bs02 is just a plain old string. I used to import simple integers and in that case i had to use bs02.toint() to convert the string into an int, but now since the string is 2 letters or numbers combined in one string i can't just use .toint().

Would it be way better if i just used a 2 char array instead of the string?

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [March 29, 2015, 6:39am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/8 "2015-03-29T06:39:34Z")

</div>

> Would it be way better if i just used a 2 char array instead of the string?

It would be most memory efficient if it were in a null terminated array of chars. Please, if you are going to refer to 'strings' use capital S if it is a String created using the String library.

---

<div class="post-metadata">

**Author:** ![giantsquid](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@giantsquid](https://forum.arduino.cc/u/giantsquid)\
**Post date:** [April 2, 2015, 3:30am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/9 "2015-04-02T03:30:33Z")

</div>

wow ok, I didn't know arduino handled "String" and "string" differently. Oh my. Good to know!

---

<div class="post-metadata">

**Author:** ![giantsquid](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@giantsquid](https://forum.arduino.cc/u/giantsquid)\
**Post date:** [April 2, 2015, 5:55am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/10 "2015-04-02T05:55:49Z")

</div>

To clarify my question, if i have 2 chars, "c[0]" and "c[1]" that both hold hex values and together they are a two digit hex val FF, how do i convert that to 255?

@econjack I'm sorry but I just didn't understand the answer you gave me

---

<div class="post-metadata">

**Author:** ![guix](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/guix/32/215371_2.png) [@guix](https://forum.arduino.cc/u/guix)\
**Post date:** [April 2, 2015, 7:43am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/11 "2015-04-02T07:43:29Z")

</div>

See reply #2

---

<div class="post-metadata">

**Author:** ![giantsquid](https://avatars.discourse-cdn.com/v4/letter/g/d07c76/32.png) [@giantsquid](https://forum.arduino.cc/u/giantsquid)\
**Post date:** [April 2, 2015, 9:30am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/12 "2015-04-02T09:30:07Z")

</div>

could you possibly elaborate, please?  
also, the problem isn't just converting a single hex char to integer, but the fact that i have two separate strings, c[0] and c[1] that need to be combined together to a single string and then converted to int

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [April 2, 2015, 10:12am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/13 "2015-04-02T10:12:28Z")

</div>

> To clarify my question, if i have 2 chars, "c[0]" and "c[1]" that both hold hex values and together they are a two digit hex val FF, how do i convert that to 255?

Try something along these lines maybe...

```arduino
char hexValue[] = {'F', 'F'};

void setup()
{
  Serial.begin(115200);

  byte tens = (hexValue[0] < '9') ? hexValue[0] - '0' : hexValue[0] - '7';
  byte ones = (hexValue[1] < '9') ? hexValue[1] - '0' : hexValue[1] - '7';
  byte number = (16 * tens) + ones;
  Serial.println(number);
}

void loop()
{
}

```

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1290082_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [April 2, 2015, 12:02pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/14 "2015-04-02T12:02:00Z")

</div>

> @econjack I'm sorry but I just didn't understand the answer you gave me

Take the program that I wrote, compile and run it. Then run the Serial monitor (Tools --\> Serial Monitor) and type two hex digits into the top box and click Send and observe the output. The function I wrote, _StrToHex()_, does nothing but call the standard library function _strtol()_, which converts a string to a _long_. However, a _long_ is 4 bytes and you want an _int_ which is two bytes. Simply trying to pour 4 bytes of data (i.e., the _long_) into a 2-byte bucket (i.e., the _int_) runs of the risk of losing information. When that situation is possible, you should use a cast, which is what the expression _(int)_ does before returning from the function call.

Spend a little time studying that program and a lot of what the others have said here will make more sense.

---

<div class="post-metadata">

**Author:** ![christop](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/christop/32/1013044_2.png) [@christop](https://forum.arduino.cc/u/christop)\
**Post date:** [April 2, 2015, 6:07pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/15 "2015-04-02T18:07:54Z")

</div>

> econjack:
> 
> ```arduino
> int StrToHex(char str[])
> 
> ```

{  
&nbsp;return (int) strtol(str, 0, 16);  
}

> ```arduino
> 
> ```

That type cast is not needed. The value returned from strtol() will automatically be converted to int when it's returned from StrToHex(). I believe it's best not to use a type cast unless you understand why it's needed--otherwise you run the risk of suppressing compiler warnings that expose actual bugs in your code.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [April 2, 2015, 6:20pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/16 "2015-04-02T18:20:09Z")

</div>

> you run the risk of suppressing compiler warnings that expose actual bugs in your code

The IDE is already pretty effective at suppressing warnings

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1290082_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [April 2, 2015, 6:26pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/17 "2015-04-02T18:26:16Z")

</div>

> I believe it's best not to use a type cast unless you understand why it's needed--otherwise you run the risk of suppressing compiler warnings that expose actual bugs in your code.

True, but the sequence point is usually the reverse: the code doesn't work as expected because the cast is missing. As to my use of the cast, it's really there for documentation purposes since, as you mentioned, the function type specifier will force it to an _int_ anyway. That's what I call a "silent cast" which I am not a big fan of. A silent cast occurs when you assign a smaller data type (e.g., a 2-byte _int_) into a larger data type (e.g., a 4-byte _long_). Even though the compiler doesn't complain in those cases, I would still use the cast to document the intent. If they don't understand what a cast is, they probably have other fish to fry.

---

<div class="post-metadata">

**Author:** ![christop](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/christop/32/1013044_2.png) [@christop](https://forum.arduino.cc/u/christop)\
**Post date:** [April 2, 2015, 6:50pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/18 "2015-04-02T18:50:55Z")

</div>

> AWOL:  
> The IDE is already pretty effective at suppressing warnings

LOL. That's true enough.

The verbose compiling option in the Arduino IDE would be a lot more attractive to use if some of the built-in libraries themselves (I'm looking at you, HardwareSerial.cpp) didn't throw compiler warnings. I bet the Arduino library developers don't even use verbose compiling because the warnings are so simple and easy to fix, like "comparison between signed and unsigned integer expressions".

---

<div class="post-metadata">

**Author:** ![christop](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/christop/32/1013044_2.png) [@christop](https://forum.arduino.cc/u/christop)\
**Post date:** [April 2, 2015, 6:55pm UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/19 "2015-04-02T18:55:49Z")

</div>

> econjack:  
> True, but the sequence point is usually the reverse: the code doesn't work as expected because the cast is missing.

Yeah, there are cases where a cast is needed, such as to expand an integer to a larger (or smaller) type inside an expression. But as I said--"it's best not to use a type cast unless you understand why it's needed".

---

<div class="post-metadata">

**Author:** ![davros](https://avatars.discourse-cdn.com/v4/letter/d/c89c15/32.png) [@davros](https://forum.arduino.cc/u/davros)\
**Post date:** [April 21, 2015, 6:28am UTC](https://forum.arduino.cc/t/convert-hex-string-to-int/301014/20 "2015-04-21T06:28:59Z")

</div>

econjack, I think I've missed something in your code on reply #3. It is only converting 1 character at a time. Entering "FF" into serial monitor gets a response of  
Hex input was: F decimal = 15  
Hex input was: F decimal = 15

instead of  
Hex input was: FF decimal = 255

Any ideas what it could be?

[Next page](https://forum.arduino.cc/t/convert-hex-string-to-int/301014.md?page=2)
