Home >Common Problem >What are the methods of converting decimal to hexadecimal in C language?
Methods for converting decimal to hexadecimal in C language: 1. Through the while loop method; 2. Through the for loop method; 3. Use functions to convert, code such as "int decimal_to_hexadecimal(int x)" .
The operating environment of this article: Windows 7 system, version C11, Dell G3 computer.
There are many ways to convert decimal to hexadecimal in C language. You can use for loops, while loops, or functions. Let's take a look at the specific method introduction
The decimal number has base 10 and includes the following numbers: 0 1 2 3 4 5 6 7 8 9
The hexadecimal number has Base 16 and includes the following values: 0 1 2 3 4 5 6 7 8 9 A B C D E F, where A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.
The code for converting decimal to hexadecimal in C language is as follows
while loop:
#include<stdio.h> int main() { long int decimalNumber,remainder,quotient; int i=1,j,temp; char hexadecimalNumber[100]; printf("输入十进制数任意: "); scanf("%ld",&decimalNumber); quotient = decimalNumber; while(quotient!=0) { temp = quotient % 16; if( temp < 10) temp =temp + 48; else temp = temp + 55; hexadecimalNumber[i++]= temp; quotient = quotient / 16; } printf("十进制数的等效十六进制值 %d: ",decimalNumber); for (j = i -1 ;j> 0;j--) printf("%c",hexadecimalNumber[j]); return 0; }
for loop
#include<stdio.h> #include<math.h> int main() { int decimal_number, remainder, hexadecimal_number = 0; int count; printf("Enter a Decimal Number:\t"); scanf("%d", &decimal_number); for(count = 0; decimal_number > 0; count++) { remainder = decimal_number % 16; hexadecimal_number = hexadecimal_number + remainder * pow(10, count); decimal_number = decimal_number / 16; } printf("\nHexadecimal Equivalent:\t%d\n", hexadecimal_number); return 0; }
Use function
#include<stdio.h> #include<math.h> int decimal_to_hexadecimal(int x) { int hexadecimal_number, remainder, count = 0; for(count = 0; x > 0; count++) { remainder = x % 16; hexadecimal_number = hexadecimal_number + remainder * pow(10, count); x = x / 16; } return hexadecimal_number; } int main() { int decimal_number, result; printf("Enter a Decimal Number:\t"); scanf("%d", &decimal_number); result = decimal_to_hexadecimal(decimal_number); printf("\nHexadecimal Equivalent:\t%d\n", result); return 0; }
The above is the detailed content of What are the methods of converting decimal to hexadecimal in C language?. For more information, please follow other related articles on the PHP Chinese website!