Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need function to convert char string to int -- Help Please -- Thanks

Status
Not open for further replies.

DougCa

Technical User
Nov 1, 2002
13
0
0
US
Hi all:

I need a function to do the following. To take a char buffer of 14 octal bytes. These byes represent ASCII characters.

Take the buffer and convert the last four bytes to an integer (bytes 10,11,12 and 13). The ETX (\003) is byte 14 on the end. buf2 is char buf2[14]

buf2 contains \002\006\105\060\060\060\060\060\060\106\106\105\061\003

For example:

31 converts from \060\060\061\106 (i.e. 001F in Ascii)
-31 converts from \106\106\105\061 (i.e. FFE1 in Ascii)
0 converts from \060\060\060\060
7 converts from \060\060\060\007
15 convers from \060\060\060\106

If you look at an ASCI to octal table it will make sense.

I need the four chars in the last two bytes (10,11,12,13) to be converted to an interger.

Thanks,
DougC
 
did you try useing the atoi function? an integer can hold a octal value and knows it is holding an octal value if there is a 0 in front of it. just not sure if atoi will interpret it correctly.
 
well if atoi doesnt work, you may have to do some octal or hex math. in base 10, each digit farther to the left of the decimal gets multiplied by a multiple of 10.

ascii value of 1 is 49. so to convert a char cOne = '1' to int iOne = 1. you do something like

if(isdigit(cOne))
iOne = (int)cOne - 48.

example: char someNum[] = "234";

pick off the right most digit. convert it to an integer number by taking the ascii value of it and subtracting the amount of offset (i think that is 48). and multiply it by 1. the pick off the second, convert it and multiply it by 10 and the third by 100. do an accumulation in a loop as you do the multiplication.

you do the same for octal and hex but you use a different base. so instead of multiplying by 1, 10, 100. you multiply by 1, 8, 64.

and further, if you represent your base as 2 raised to a power that increments sequentially, you dont have to limit how many digits are in your number. and you dont have to calculate what comes after 64. 2^3, 2^6, 2^9

but thats a lotta thinking to do. so if you can get atoi to work and maybe use sprintf, then you will save on brain power.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top