將整數轉換為 C ++ 中的十六進位制字串
在這個程式中,我們將瞭解如何將一個整數轉換為一個十六進位制字串。要將一個整數轉換為十六進位制字串,我們可以按照數學步驟進行。但在這個案例中,我們使用一個簡單的技巧解決了這個問題。
在 C/C++ 中,有一個格式說明符 %X。它以十六進位制形式列印某個變數的值。我們使用這個格式說明符透過使用 sprintf() 函式將數字轉換為一個字串。
Input: An integer number 255 Output: FF
演算法
Step 1:Take a number from the user Step 2: Make a string after converting number using %X format specifier Step 3: Print the result. Step 4: End
示例程式碼
#include<iostream> using namespace std; main() { int n; char hex_string[20]; cout << "Enter a number: "; cin >> n; sprintf(hex_string, "%X", n); //convert number to hex cout << hex_string; }
輸出
Enter a number: 250 FA
廣告