Solved

Numeric i/o

Posted on 2004-03-21
13
260 Views
Last Modified: 2010-04-15
Im a fairly new c programmer. Ive done abit of programming but not much. Any comments or solutions are needed please.

Im wanting to create a file that converts between the character string representation of a number and its machine representation.

Im wanting to use three functions to do this... adding greater functionality to the file. First of all I think I could use the itoa() function to do the conversion.

For example:
char *itoa(int n);
this would convert n into its character string representation in the current number base (between 2 and 36) and would return the address of the string.

The first funtion I want to have in the file would be:

void setbase(int n);
This function sets the number base. If 1<b and b<37 then the number base would be set. A error would be invoked if the number base is not in the range.

int getbase();
I would want this function to return the current valeu of the i/o number base.

int convert(char string[]);
providing the number base is set between 2 and 36, this function would need to convert the described string in the current base to its machine representation. If the number base is not recognised and not in the range... a error would need to be reported and would return any value.
0
Comment
Question by:philb2013046
13 Comments
 
LVL 4

Expert Comment

by:ArcaArtem
ID: 10643889
Hello,

Could you elaborate and explain more about what you want to achieve? What exactly do you mean by "its machine representation"? Binary? Or are you tring to write a conversion routine that will take a number in any base and convert it to base-10?

Arca
0
 

Author Comment

by:philb2013046
ID: 10644208
Overall, I want the program to acieve the conversion of a string of numbers, to its string representation in the current number base, set in the setbase() function.
0
 
LVL 45

Expert Comment

by:Kdo
ID: 10644414
Hi philb2013146,  (Mind if I all you "Phil"?)

Half of what you want to do is already built into the C library.  Check out itoa() and its related functions like ltoa().  These functions convert binary integers to ascii strings in the specified base.

Performing the conversion in the other direction (from an ascii string to a binary integer) is just as easy.  Assume that your number system consists of the digits 0 - 9, and then sufficient letters in the range A - Z to generate the required number of digits.  (Just like we do with base 16 which uses the digits 0 - 9 and the letter A - F.)  Then converting a string to an integer is a small loop:

long atol (char *string, int base)
{
  long value = 0;
  while (*string)
  {
    value *= base;
    if (isdigit (*string))
      value += (*string - '0');
    else
      value += ((*string - 'A') + 10);
    string++;
  }
  return value;
}

This sounds like homework, so I can't wrap it up too neatly for you.  The function needs sanity checks like valid digits, upper/lower case support, etc.

Good Luck!
Kent

0
 
LVL 2

Expert Comment

by:Avik77
ID: 10644657
>> Half of what you want to do is already built into the C library.

I feel the total of it is there.

#include<stdlib.h>
void main()
{
 char s[]="16",dest[16];//say
 int temp,base=2; //say
 temp=atoi(s);
 itoa(temp,dest,base); /* base can come from ur setbase() function also */
 // ur result in dest now !
}
0
 
LVL 45

Expert Comment

by:Kdo
ID: 10644743
Hi Avik,

I'm not familiar with any C function that will convert a string to an arbitrary based number.  What API or protocol do you have in mind?

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:philb2013046
ID: 10644779
The file needs to be set out and structured using the above layout.
0
 
LVL 45

Expert Comment

by:Kdo
ID: 10644830
Hi Phil,

No one here is going to do you homework for you.  I've laid out one of the functions for you, but that's as far as the rules of the board allow me to go until you make a sincere effort to do this yourself.

If you've got specific questions, ask away.  Otherwise, you need to attempt this yourself.  If you get stuck anywhere along the way I'll be glad to help.

Give it a try.  It's really not that tough.


Kent
0
 

Author Comment

by:philb2013046
ID: 10645965
I have sort of had a crack at giving an outline of what I want the program to do. I know theres many mistakes and other stuff wrong with it but its only to give an idea.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*#ifndef NUMBER_H*/
#define NUMBER_H

int convert(char string []);
int getbase(); /*I would like this function to return the current i/o number base*/
void setbase(int n);
char *itoa(char *string[]);

int main(void)
{
  int base;
  int *bptr = &base; /*pointer assigned to base*/
  int *sptr;         /*pointer for the string*/
  char string[]="16",dest[16];
  int *temp;
  setbase();
  printf("The base has been set to %d", base);

  if (bptr >1) && (bptr <37)
     temp = convert(char string[])    /*convert the number described in string*/
  else
     printf("report_error");

  printf("The string %s, was converted to %s.\n ", string, dest);

  return 0;
 }

void setbase() /*allows you to set the base*/
{
  int *nptr;
  int n;
  nptr = &n;
  n=0;

  printf("Input the number base");
  scanf("%d", bptr);
 }

int convert()  /*the functions converts the string using the set base*/
{
 temp = atoi(string);
 itoa(&temp, &dest, &base);

 }

Any suggestions on what to do next or what I need to do to it are very welcome. Thank you.
0
 
LVL 45

Expert Comment

by:Kdo
ID: 10646201

Hey -- this is a pretty good start.  It's clear that you're new to this, but that's OK.  :)

Here's your program again.  I haven't really changed anything that you've done, but I have documented what else you need to do.  My comments start with '//' to make them easy to spot.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>


// You don't need to define NUMBER_H in this manner.  (I would omit the definition completely.)
// There's nothing wrong with doing this, but it looks like you're trying to control
// compiler expansion as if this were a header file.

// Also, #if, #ifdef, #ifndef, etc should all have matching #endif statements


/*#ifndef NUMBER_H*/
#define NUMBER_H


// Function prototypes.  Very good.  Most people take shortcuts and skip this part!

// I would suggest that you change the name of the convert() function.  Because you
// need to convert from ascii to integer and from integer to ascii, you should
// probably select names that are a bit more descript.  What other functions are
// you going to need?


int convert(char string []);
int getbase(); /*I would like this function to return the current i/o number base*/
void setbase(int n);
char *itoa(char *string[]);

// For the program that you've described, you probably want to use the command line
// parameters for input.  'int main (int argc, char *argv[])' should be used to
// allow the program to access these parameters.


int main(void)
{

// Some of these variables may be better suited to being global variables.  Either
// that or plan to pass them to every function.

  int base;
  int *bptr = &base; /*pointer assigned to base*/
  int *sptr;         /*pointer for the string*/
  char string[]="16",dest[16];
  int *temp;

// main() is usually a pretty simple routine.  It is a lot "neater" if it does almost
// none of the work, but calls the functions that do.


// Your prototype for setbase() says that you're going to pass an integer.  Here you
// call setbase() without a parameter.  What is the base going to be?

  setbase();
  printf("The base has been set to %d", base);

  if (bptr >1) && (bptr <37)
     temp = convert(char string[])    /*convert the number described in string*/
  else
     printf("report_error");

  printf("The string %s, was converted to %s.\n ", string, dest);

  return 0;
 }

// setbase() cannot set the variable 'base' in the main() function.  You'll have to
// return the base value from this function to do that.  Or make 'base' a global
// variable.

void setbase() /*allows you to set the base*/
{
  int *nptr;
  int n;
  nptr = &n;
  n=0;

  printf("Input the number base");
  scanf("%d", bptr);
 }

// There are several problems with this function.  temp is undefined.  Also, the
// function should probably return a value so that main() can set the value into
// the correct variable.


int convert()  /*the functions converts the string using the set base*/
{
 temp = atoi(string);
 itoa(&temp, &dest, &base);

 }



If you'll clean up the things that I've described here, your program will be a lot closer to functional.  There are still several things to address, but let's walk before we run.  :)


Kent
0
 

Author Comment

by:philb2013046
ID: 10649487
I have had a go at tidying the program but have totally confused myself and have came to a complete hault. I know what I want to do but just can't translate it into C. I have tried to make changes you have suggested but only managed to confuse myself. So far this is what I have now got:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#ifndef NUMBER_H

int convert(char string []);
int getbase();
void setbase(int n);
char *itoa(char *string[]);

int main(int argc, char *argv[])
{
  char *string[]="16",dest[16];
  int *temp;
  int n = *string[];
  int b;
  setbase();
  printf("The base has been set to %d", b);     /*check if base has been set*/

  if (b >1) && (b <37)                /*test if in range of 2-36*/
     temp = convert(char string[])    /*convert the number described in string*/
  else
     printf("report_error");

  printf("The string %s, was converted to %s.\n ", string, dest); /*result conversion*/

  return 0;
 }

void setbase(int n, int b, int temp) /*allows you to set the base*/
{
  b = 0;          /*base*/
  /*int *bptr = &b; pointer assigned to base*/  /*wasnt sure what to do here*/
  n=0;                                          /*whether to use a pointer or not*/
  int *nptr;

  printf("Input the number base");  /*user defined base*/
  scanf("%d", b);

  return (b);                       /*return b to main*/
 }

int convert(char string[])  /*the functions converts the string using the set base*/
{
 temp = atoi(string);       /*conversion*/
 itoa(&temp, &dest, &b);

 }

#endif

Doesnt look great and neither works at all which isnt a surprise. I think Im just taking it too quickly and doing too much at a time, therefore confusing myself!
0
 
LVL 45

Accepted Solution

by:
Kdo earned 125 total points
ID: 10649655
Hi Phil,

You're certainly struggling with this.  I'm going to make a few changes to help you along.  Perhaps seeing how some of this works will help.

The program will be used like this:

Program Number Base

For example:

MyProg 15672 8
MyProg 4b312aE 16
MyProg 010110101010 2
etc....


#include <string.h>
#include <stdio.h>
#include <stdlib.h>


int convert(char string []);
int getbase();
void setbase(int n);
char *itoa(char *string[]);

int main(int argc, char *argv[])
{
  int base;
  char *string[]="16",dest[16];
  int *temp;
  int n = *string[];
  int b;

  if (argc != 3) /* Check for command line arguments */
  {
    printf ("Usage:  %s Number Base\n", argv[0]);
    exit (0);
  }

  base = setbase (atoi (argv[2]));                    /* set the base from the second parameter  */
  printf ("The base has been set to %d", b);     /*check if base has been set*/

  if (b >1) && (b <37)                /* test if in range of 2-36*/
     temp = convert (argv[1])      /* convert the number in the first parameter */
  else
     printf ("report_error");

  printf ("The string %s, was converted to %s.\n ", string, dest); /*result conversion*/

  return 0;
}

void setbase (int b) /*allows you to set the base*/
{
  return (b);                       /*return b to main*/
}

int convert (char string[], int base)  /*the functions converts the string using the set base*/
{
  long value = 0;
  int    idx = 0;

  while (string[idx])
  {
    value *= base;
    if (isdigit (string[idx]))
      value += (*string[idx] - '0');
    else
      value += ((string[idx] - 'A') + 10);
    idx++;
  }
  return value;
}



This should be pretty close, for starters...

Kent
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now