Thursday, August 27, 2015

Dec 2 hex.

if you wanted to convert a decimal number to a hexadecimal number, you can do it several ways. first you could do it the old fashion way by hand.


or you could use a C language program such as:

[code]
  #include<stdio.h>
int main(){
    long int decimalNumber,remainder,quotient;
    int i=1,j,temp;
    char hexadecimalNumber[100];

    printf("Enter any decimal number: ");
    scanf("%ld",&decimalNumber);

    quotient = decimalNumber;

    while(quotient!=0){
         temp = quotient % 16;

      //To convert integer into character
      if( temp < 10)
           temp =temp + 48;
      else
         temp = temp + 55;

      hexadecimalNumber[i++]= temp;
      quotient = quotient / 16;
  }

    printf("Equivalent hexadecimal value of decimal number %d: ",decimalNumber);
    for(j = i -1 ;j> 0;j--)
      printf("%c",hexadecimalNumber[j]);

        printf("\n");
    return 0;
}
[/code]

Compile it  and then run it:

$ ./d2h
Enter any decimal number: 708
Equivalent hexadecimal value of decimal number 708: 2C4

or actually you could use either of two command line commands.

$ echo 'obase=16;ibase=10;708'| bc
2C4

or

$ printf '%x\n' 708
2c4

As you learn bash, you can see you can do things without getting real complicated.

No comments:

Post a Comment