-1

The string variable will contain a hexadecimal, which we need to safely place in the uint16_t?

Example:

String hexa = "0x11A0";
uint16_t num = ???;

Remember, I dont need to conversion to decimal here.
i.e. my requirement is, unint16_t num = 0x11A0;. I need to convert to an unint16_t from a hexadecimal.

unint16_t can contain 0x11A0, but however my problem is that I cant get the value from a string variable and save it in unint16_t.

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182

2 Answers2

0

You want to convert a string containing a hexadecimal representation of an integer to an integer?

strtol can do that.

Remember, integers inside the Arduino are binary numbers. We care about binary, decimal, octal, and hexadecimal only when presenting values to humans. Most microprocessors operate on binary values.

So, include a file at the top of your script, and use the strtol function to convert the string to an integer. By using 0 for the base argument, it will handle decimal, octal, and hexadecimal formatted values.

#include <stdlib.h>
...
// we use .c_str() to access the underlying C string
int16_t x = strtol(hexa.c_str(), NULL, 0);
aMike
  • 852
  • 5
  • 14
  • I understand what you are implying, but this is not helping to solve the problem. See when I do what you have suggested, the int16_t contains the long integer only, but however I want the hexadecimal itself to be placed in the int16_t. The reason why I am sure it is possible, is because I am able to save a hexadecimal to int16_t directly, that is int16_t = 0x11A0, but cant get a hexadecimal from string and save it to int16_t. – Vinayagamany Sathiyakumar Jul 13 '17 at 10:29
0
 const short MaxSubs=10;
 uint16_t Subs[MaxSubs];

  String myStr=String(Node, HEX);
  short n=myStr.length();
  short k=n;
  while(n>0)
  {
    String sub=myStr.substring(k, n--);
    Subs[n]=strtol(sub.c_str(), NULL, 0); 
    delay(50);`
    printf_P(PSTR("%lu: Sub %h \n\r"), millis(), Subs[n]);
  }
MAhipal Singh
  • 4,745
  • 1
  • 42
  • 57