-1

i have a problem and hope you guys can help me. I am using an 32 bits uC for my project. I receive characters over the Uart from the keyboard to the uC (via Hyper Terminal). Because i only use C, i am storing this characters into an buffer of type char. For example i need to send an address in hexadecimal as a input , something like 0xff502035. I sent it with Hyper Terminal over the Uart, and store it char by char inside my buffer. Then i want to convert this to an integer number (from char) in order to pass it further to my functions which will read the value stored at that location.

So what i need is something like : convert char[] into an int. So if my buffer contains "0xff502035" , i need it as 0xff502035 integer type. Thank you guys in advance for helping me.

Best regards, Laurentiu

Laurentiu
  • 143
  • 1
  • 2
  • 8

2 Answers2

0

I'm not going to provide a full sample of "how to convert a string to number", but have a look at the strtol function.

slugonamission
  • 9,562
  • 1
  • 34
  • 41
  • Hello, thanks a lot for the hint. i have tried, but i am facing one small problem.. if i enter an string like "0xf5f500" it converts it correctly but for a string like "0xf5f500ff" if give a totally wrong values ? any ideas why ?? thanks – Laurentiu Feb 28 '13 at 13:36
  • @Laurentiu It'll be because you're assigning it to an int. Given it's a 32-bit uC, an int's range of positive values is from 0x00000000 - 0x7FFFFFFF, where the top bit is used as the "sign bit" (or rather, is equivalent to negative 2mil or so), look up two's compliment numbers to see why. The input string you give is outside this range, and thus will be a negative number. Short answer is, use a longer data type or mark your int as unsigned. – slugonamission Feb 28 '13 at 17:56
  • Thanks for the answer. The problem is i tried both making it a unsigned int or long data type but the output is the same...0x7FFFFFFF. I was ill but today i will investigate further this problem... – Laurentiu Mar 04 '13 at 08:54
0

This has been answered on this forum, link above.

However, completing the post, while the address has been recorded in a hex format and transferred as a string, it actually is an address that is interpreted finally in binary format. The function strtoul, can be used safely on both 32-bit and 64-bit systems to convert addresses in hex format back to the original form.

char *buf; // Contains the address in string format

char *endptr;

int *ptr;

ptr = (int*)strtoul(buf, &endptr, 16);