Solved

Simple Base Number Converter

Posted on 2003-10-23
8
555 Views
Last Modified: 2010-08-05
I just started learning C programming and we just finished learning about function calls and base conversion.  Can you give me a simple program that converts a decimal based integer (user input) to binary, octal, and hexadecimal bases? It can't have printf %o (octal) or %x (hexidecimal).  Just a simple program for someone who just started learning about programming and learning about calling a function.

I'd really appreciate it.  Thanks alot!

0
Comment
Question by:cooldean
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 8

Expert Comment

by:akshayxx
ID: 9612454
few key points here,
1. all numbers are stored in binary format.
2. octal and hexadecimal are powers of 2.
3. to get bit by bit of a number, u can use the 'right-shift'( >> ) operation in C.
4. to divide a number by 2^n, right shift the number by n bits.

so here is the procedure to get the binary/octal/hexadecimal representation of the number.
keep this string of bits/octets/hex-bits
char *nbits="0123456789abcdef";

1. to get the binary representation of the number..
  right-shift bit by bit and keep storing/printing the bits one by one.
  (for each shifted bit print---> nbits[value_of_shifted_bit]; )
2. to get the octal representation of the number..
  right-shift the number by 3-bits at a time, and each time checking the number in the thus got 3 shifted bits, and print the appropriate octet.
  (for each shifted bit print---> nbits[value_of_shifted_bits]; )

3. for hexadecimal, shift the bits 4 at a time
  (for each shifted bit print---> nbits[value_of_shifted_bits]; )

the number that u'll print this way will be in the right-to-left direction ( reversed from normal left-to-right)

try implementing code on this and we will help you out to make it work.

akshay

0
 
LVL 8

Expert Comment

by:akshayxx
ID: 9612521
ok let me give you an code-snippet example for printing the octal representation

#define OCT_MASK 0x07  //largest possible number represented by a single octal-digit(octet)
unsigned int num=0xffffffff;  // this is a sample 32 bit number
int nBits=3;  //number of bits to skip each time.. for octal it is 3, for hex it is 4, for binary it is 1.
int max_bits=8*sizeof(int); // number of bits in the integer on this platform
char *digit_char="0123456789abcdef";
int digit;
for(i=0;i<max_bits;i+=nBits){

digit=num & OCT_MASK; // take the number in the right most 3 bits
printf("%c",digit_char[digit]);
num= num>>nBits; //drop of the last 3 bits
}

above loop will print the octets of num from right to left, to print them in the left-to-right order, u may keep storing the octets in the array...and print it later on

for hexadecimal representation use
#define HEX_MASK 0x0f
and nBits=4

for binary representation use
#define BIN_MASK 0x01
and nBits=1

change the other part of the codes accrodingly, try to bring together all this in a program, better will be to make a function which takes in the argument to choose from oct/hex/bin and return the appropriate character string
good luck
akshay
0
 

Author Comment

by:cooldean
ID: 9613539
Hmm...thanks for the help but I'm having a hard time following your suggestions.  We haven't learned nBits.  We just started C Programming so I don't know how to use it, and what is 0x0f or 0x01.  I haven't learned using the size value like that.  I just learned it like: SIZE 100 or SIZE 50, but not with 0x0f.

Is there another simpler way?

Again, thanks alot.
0
 
LVL 4

Accepted Solution

by:
dhyanesh earned 350 total points
ID: 9616282
hi

Another method to convert to another base is to find the remainder when the number is divided by the base i.e. by 2, 8, 16 for binary, octal and hexadecimal.

sample code for binary would be somewhat like:

while (num > 0)
{
    x = num % 2;   //gets the remainder when number is divided by 2
    num = num / 2;
    array[i] = x + '0';       //array is character array so we have to add ascii value of 0 to store correctly
    i++;
}

//Now reverse the array

for(j=0;j < i/2 ;j++)
{
    temp = array[j];
    array[j] = array[i-j-1];
    array[i-j-1] = temp;
}

Similarly you can do for octal and hex. For octal you have to divide by 8 and for hex by 16. For hex you have to check whether remainder is > 9. If it is you have to convert it to A,B,C,D,E,F and then store.

Dhyanesh
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:cooldean
ID: 9616380
Thanks alot.

But got two questions:

Can you do this without using arrays?  I know it might be a longer way but how do you do it?  I tried to figure it out.

Second, when I tried to run your (Dhyanesh) program, I got errors saying that I need pointers for the arrays.  That's the reason I don't really want to use arrays.  My question is: I'm learning functions calls and if I add your program, would it be the function at the top and I would just need to call it at my void main function?

Again, I really appreciate your help.

-cooldean
0
 
LVL 4

Expert Comment

by:dhyanesh
ID: 9616825
hi

if you wish to do without arrays it will be somewhat like:

binary = 0;
mult = 1;
while (num > 0)
{
   x = num % 2;   //gets the remainder when number is divided by 2
   num = num / 2;
   binary = mult *x + binary;       //binary is integer variable
   mult = mult * 10;
}

return binary;

However this will not work for hexadecimal as it involves A,B,C,D,E,F which require a char array to store.

>>would it be the function at the top and I would just need to call it at my void main function?

You can create a function on top of main or even after the end of main. If you create it before main you just need to call the function in main. However if you write function after closing brace of main you require a function prototype in the main before you call it i.e.

void main()
{
     int func1(int); //function prototype
.....

    abc = func1(xyz);
}

int func1(int t)
{
    ................
}

Dhyanesh
0
 
LVL 4

Expert Comment

by:dhyanesh
ID: 9616868
hi

another way to do it would be by using recursion.(function calling itself)


void binary(int n)
{
     if (n>0)
     {
      binary(n/2);
      printf("%d",n%2);
     }
}

this function is called from the main.

similar for octal and hex. and for hex again you will have to check if remainder > 9 etc..

Dhyanesh
0
 

Expert Comment

by:kkpavankumar
ID: 9622930
Try this program for a decimal(<255) to binary conversion......


#include<stdio.h>
#include<conio.h>


typedef struct byte
{
      unsigned int fi : 1; //First bit denoted by fi.
      unsigned int se : 1; //Second bit denoted by se.
      unsigned int th : 1; //Third bit denoted by th.
      unsigned int fo : 1; //Fourth bit denoted by fo.
      unsigned int ff : 1; //Fifth bit denoted by ff.
      unsigned int si : 1; //Sixth bit denoted by si.
      unsigned int sv : 1; //Seventh bit denoted by sv.
      unsigned int ei : 1; //Eighth bit denoted by ei.
} byte;
byte test;

void byte_print(byte);
void convert_byte(int);

void main()
{
      int a;
//      struct byte test;
      printf("Enter the number < 255 to be converted to binary");
      scanf("%d", &a);
      convert_byte(a);
      byte_print(test);
      getch();
}

void convert_byte(int x)
{
      int i;
//      extern byte test;
      test.fi = x & 1;
      x >>= 1;
      test.se = x & 1;
      x >>= 1;
      test.th = x & 1;
      x >>= 1;
      test.fo = x & 1;
      x >>= 1;
      test.ff = x & 1;
      x >>= 1;
      test.si = x & 1;
      x >>= 1;
      test.sv = x & 1;
      x >>= 1;
      test.ei = x & 1;
      x >>= 1;
}

void byte_print(byte x)
{
 printf("\n%d",x.ei);
 printf("%d",x.sv);
 printf("%d",x.si);
 printf("%d",x.ff);
 printf("%d",x.fo);
 printf("%d",x.th);
 printf("%d",x.se);
 printf("%d\n",x.fi);
}
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

744 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

11 Experts available now in Live!

Get 1:1 Help Now