| | |
Decimal to Base 2 - 16 Conversion
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Let's expand the decimal to binary converter to include, amongst others, octal and hexadecimal conversions. Also shows how to exert some input control. Simple stuff!
// Convert a positive decimal integer to a number of base (2 to 16) // Also a good example for using do ... while() to check input // tested with Pelles C vegaseat 1dec2004 #include <stdio.h> char *conv_base(long number, int base); int main() { int base; long number; char yn; do { do { printf("\n\nEnter an integer number : "); scanf("%ld",&number); } while (number < 1); // positive integers only do { printf("\nEnter the base (2-16) : "); scanf("%d",&base); } while (base < 2 || base > 16); // stay in range printf("\nThe converted number is : %s",conv_base(number,base)); printf("\n\n Any more (y/n) : "); getchar(); // a little goofy but needed yn = getchar(); } while (!(yn == 'n' || yn == 'N')); return 0; } char *conv_base(long number, int base) { long remain; int n = 0, k = 0; static char temp[32], result[32]; static char *digit = "0123456789ABCDEF"; // list of digits do { remain = number % base; // modulo gets remainder number = number / base; // whittle down number temp[k++] = digit[remain]; } while (number > 0); while (k >= 0) { result[n++] = temp[--k]; // spell forward } result[n-1] = 0; // add string EOS return (result); }
Similar Threads
- Binary (base 2) to Decimal (base 10) HELP! (C)
- Base Conversion (Java)
- Convert decimal to binary and with base the 8 (C)
- Base conversion (C)
- base conversion (Java)
| Thread Tools | Search this Thread |
Tag cloud for C
#include * .net append array arrays asterisks binarysearch calculate changingto char character cm command copyimagefile cprogramme creafecopyofanytypeoffileinc database directory dynamic execv feet fgets file fork forloop framework function functions givemetehcodez grade graphics gtkwinlinux hacking histogram homework include incrementoperators input intmain() iso kernel keyboard km lazy license linked linkedlist linux list lists locate logical_drives looping loopinsideloop. lowest matrix microsoft mqqueue mysql number oddnumber odf opensource overwrite owf pdf performance pointer pointers posix probleminc process program programming radix recursion recv recvblocked research reversing scanf scripting segmentationfault sequential socket spoonfeeding standard string student systemcall testing threads turboc unix user variable wab whythiscodecausesegmentationfault windowsapi



