-
Dec, Hex, Bin
Hi, havent had much exp. in this department, but here goes...
I have a string that will contain either all decimal chars, hexadecimal chars, or binary charcter and ill need to change that string from one (dec, hex or bin) to the other (dec, hex or binary). In the program, Ill know which type (dec, hex or bin) the string will contain. How do i go about doing this?
-
If it's a number, then can you use something like atoi/itoa to convert it to a long using the correct radix, and then back to a string with the new one?
-
Will that work if its a hex and binary number? Remember hex contains a - f.
-
No idea :) If you prefix it with 0x and pass it to atoi it should work.
-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void)
{
char oke[26] = "0xFF0";
int acker = atoi(oke);
printf("%i\n", acker);
}
I tried your suggestion, Parksie, but it didn't work. All it printed out was 0. So how do you take a string written in the hexadecimal, or octal, and use it in atoi?
-
Code:
int israddigit(char c, int rad)
{
int t;
c = tolower(c);
if(isdigit(c))
{
t = c - '0';
if(t >= rad) return 0;
else return 1;
}
if(islower(c))
{
t = c - 'a';
if(t >= rad) return 0;
else return 1;
}
return 0;
}
int raddigittoint(char c, int rad)
{
int t;
c = tolower(c);
if(isdigit(c))
{
t = c - '0';
if(t >= rad) return 0;
else return t;
}
if(islower(c))
{
t = c - 'a' + 10;
if(t >= rad) return 0;
else return t;
}
return 0;
}
int atoirad(const char* str, int rad)
{
const char* p;
int sum = 0;
for(p = str; *p && israddigit(*p, rad); p++)
{
sum *= rad;
sum += raddigittoint(*p, rad);
}
return sum;
}
that needs a lot of optimizing, but should work for ANY radix (2, 3, 4, 5, 6...)