Char to int

Go To Last Post
8 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Sorry for such a noob question :oops: :cry:/

My goal is to basically convert a char to int. I thought about using atoi, but it didn't work or I didn't use it correctly. Then I remebered atoi is for a null_terminating string. So I tried creating an array( x[2]) and I put the data into slot 0 and null terminator in slot 1 as follows

x[0] = 0x08;
x[1] = '\0';

and then I put that in atoi and I got back nothing or some crazy shape.

answer = atoi(x);

Any help will greatly be appreciated

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Try:

x[0]='8';

In the above or simply:

char x[] = "8";

in place of both lines.

Then do the atoi()

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
int x = (somechar >= '0' && somechar <= '9') ? (somechar - '0') : -1;
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ah thanks guys, that works, but I guess I didn't explain my issue very well. I was trying to change the actual char to int, for example 0x38 = 38 as an int. It's for my RTC, but I figured it out.

unsigned char x,temp;
int final;

x = 0x62;
temp = x >> 4;
temp &= 0x0F;
final = temp * 10;
temp = x & 0x0F;
final += temp;
printf("\rfinal =%i",final);

Ty for all the help though

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You actually meant a packed-BCD to binary conversion then.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
You actually meant a packed-BCD to binary conversion then.

Cool, I never knew the actual term.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

That is also called plain "BCD" or "binary coded decimal".

If 0x38 were a char, it would be the character "8" and I think that atoi would change 0x38 = "8" into 0x08.

Jim

 

Until Black Lives Matter, we do not have "All Lives Matter"!

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

0x03, 0x08 to represent 38 decimal would be BCD but putting each into the two nybbles of a single byte is "packed BCD"