Skip to content

Instantly share code, notes, and snippets.

@hcccc
Last active December 11, 2015 12:58
Show Gist options
  • Save hcccc/2b055fd7ba2b58d88c9e to your computer and use it in GitHub Desktop.
Save hcccc/2b055fd7ba2b58d88c9e to your computer and use it in GitHub Desktop.

Revisions

  1. hcccc revised this gist Feb 11, 2015. 1 changed file with 0 additions and 6 deletions.
    6 changes: 0 additions & 6 deletions hex_dec.c
    Original file line number Diff line number Diff line change
    @@ -1,9 +1,3 @@
    /**
    *@brief Print input digit in Dec, Hex and Binary form
    *@author Chuan He
    *@date 2013/01/23
    */

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
  2. hcccc created this gist Jan 23, 2013.
    48 changes: 48 additions & 0 deletions hex_dec.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    /**
    *@brief Print input digit in Dec, Hex and Binary form
    *@author Chuan He
    *@date 2013/01/23
    */

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

    #define BITMASK(n) (1 << (n))

    void divide_and_print(int x){

    printf("Dec: %d\n", x);
    printf("Hex: 0x%X\n", x);
    printf("Bin: ");

    int found_first_one = 0;
    int i = 31;

    for(i = 31; i >= 0; i--){
    if(x&BITMASK(i)){
    printf("1");
    if(found_first_one == 0){
    found_first_one = 1;
    }
    }
    else if(found_first_one){
    printf("0");
    }
    }

    printf("\n");
    }

    int main(int argc, char *argv[]){

    if(argc != 2){
    printf("[Usage]: Input a valid Dec number\n");
    return -1;
    }

    int x = atoi(argv[1]);
    divide_and_print(x);

    return 0;
    }