Skip to content

Instantly share code, notes, and snippets.

@harveytoro
Created November 8, 2012 22:35
Show Gist options
  • Save harveytoro/4042293 to your computer and use it in GitHub Desktop.
Save harveytoro/4042293 to your computer and use it in GitHub Desktop.
Decimal to any base converter
#include <stdio.h>
int main(int argc, char *argv[]) {
int userInput = 2156; //number to convert
int base = 16; // change base here
int anws[10] = {}; //couldn't get dynamic array to work. Do not like this way.
int count = 0;
do {
anws[count] = userInput % base;
userInput = userInput / base;
count++;
} while (userInput != 0);
int negcount = count - 1;
for (int i = (count -1); i >= 0; i--) {
if(anws[negcount] == 0){
negcount = 1;
continue;
}
if (base == 16){
if(anws[i] == 10){
printf("A");
continue;
}
else if(anws[i] == 11){
printf("B");
continue;
}
else if(anws[i] == 12){
printf("C");
continue;
}
else if(anws[i] == 13){
printf("D");
continue;
}
else if(anws[i] == 14){
printf("E");
continue;
}
else if(anws[i] == 15){
printf("F");
continue;
}
}
printf("%i", anws[i]);
}// for loop
}//main
import java.util.ArrayList;
class Untitled {
public static void main(String[] args) {
int userInput = 2156; //number to convert
int base = 16; // Change base here
ArrayList <Integer> anws = new ArrayList<Integer>();
int count = 0;
do {
anws.add (userInput % base);
userInput = userInput / base;
count++;
} while (userInput != 0);
for (int i = (count -1); i >= 0; i--) {
if (base == 16) {
if (anws.get(i) == 10) {
System.out.print("A");
continue;
}
if (anws.get(i) == 11) {
System.out.print("B");
continue;
}
if (anws.get(i) == 12) {
System.out.print("C");
continue;
}
if (anws.get(i) == 13) {
System.out.print("D");
continue;
}
if (anws.get(i) == 14) {
System.out.print("E");
continue;
}
if (anws.get(i) == 15) {
System.out.print("F");
continue;
}
}
System.out.print(anws.get(i));
}//for loop
}// main method
}// class
<?php
$userInput = 15; // number to convert
$base = 2; //Change base here
$anws = array();
$count = 0;
do{
$anws[$count] = $userInput % $base;
$userInput = intval($userInput / $base);
$count++;
} while($userInput != 0);
$tempnum = count($anws) ;
for ($i = $tempnum; $i >= 0 ; $i--) {
echo $anws[$i];
}
?>
@harveytoro
Copy link
Author

To convert to hex use a simple if statement within the do-while loop before $count++;

if ($base == 16){
if($anws[$count] == 10){
$anws[$count] = 'A';
}
if($anws[$count] == 11){
$anws[$count] = 'B';
}
if($anws[$count] == 12){
$anws[$count] = 'C';
}
if($anws[$count] == 13){
$anws[$count] = 'D';
}
if($anws[$count] == 14){
$anws[$count] = 'E';
}
if($anws[$count] == 15){
$anws[$count] = 'F';
}

@harveytoro
Copy link
Author

Above comment is for php only

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment