Table of Contents

Converting decimal to binary

The easiest and most straightforward approach to converting from decimal to binary is using a stack, dividing the number by two until its equal to zero and storing the remainder.

C

#include <stdio.h>
#include <stdlib.h>
 
typedef struct stack_node
{
    signed char         value;
    struct stack_node   *prev;
} stack_node_t;
 
void stack_push(stack_node_t **node, signed char value)
{
    stack_node_t *temp = NULL;
 
    temp = (stack_node_t*)malloc(sizeof(stack_node_t));
    temp->value = value;
    temp->prev = (*node);
    (*node) = temp;
}
 
signed char stack_pop(stack_node_t **node)
{
    stack_node_t *temp = NULL;
    signed char  value = 0;
 
 
    if((*node) == NULL) return -1;
 
    temp = (*node);
    value = (*node)->value;
    (*node) = (*node)->prev;
    free(temp);
 
    return value;
}
 
int stack_empty(stack_node_t **node)
{
    if((*node) == NULL) return 1;
    return 0;
 
}
 
int main(void)
{
    stack_node_t *stack = NULL;
 
    int MyMagicNumber = 154535;
    int rem           = 0;
 
    do
    {
        rem = MyMagicNumber % 2;
        MyMagicNumber = MyMagicNumber / 2;
        stack_push(&stack,rem);
    }while(MyMagicNumber > 0);    
 
    while(!stack_empty(&stack)){
        printf("%d",stack_pop(&stack));
    }
 
}

CPP

#include <iostream>
#include <stack>
 
int main(void)
{
    std::stack<signed char> m_stack;
 
    int MyMagicNumber = 154535;
    int rem           = 0;
 
    do
    {
        rem = MyMagicNumber % 2;
        MyMagicNumber = MyMagicNumber / 2;
        m_stack.push(rem);
    }while(MyMagicNumber > 0);    
 
    while(!m_stack.empty()){
        std::cout << (int)m_stack.top();
        m_stack.pop();
    }
    std::cout << std::endl;
 
}
 
d2b.txt · Last modified: 2010/01/09 15:43 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license:Public Domain
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki