C++使数字以十六进制显示

C++ make numbers appear in hexadecimal

本文关键字:十六进制 显示 数字 C++      更新时间:2023-10-16

我想让一个数字出现在十六进制字母表中,但我不知道怎么做。

例如,我使用了数字我想把号码显示为"FF FF",但它显示为"15 15"

number是我想转换的号码

base是所需的字母表(bin、dec、oct、hex)

str是带有数字的表

digitals是我有的位数

# include <iostream>
using namespace std;
class Number
{
    private:
        int number; 
        int base;
        int str[80];
        int digits;
        void    convert();
    public:
        Number(int n);
        Number(int n,int b);

printNumber打印数字

        void    printNumber();
};

convert是转换数字的函数

void    Number::convert()
{
    int icount=0;
    int x=number;
    while(x!=0)
    {
        int m=x % base;
        x=x/base;
        str[icount]=m;
        icount=icount+1;
    }

位数计数我有的位数

    digits=icount;
}

该函数使用dec 作为基础

 Number::Number(int n)
{
    number=n;
    base=10;
    convert();
}

该函数使用整数b 作为基数

Number::Number(int n,int b)
 {
    number=n;
    base=b;
    convert();
 }
void    Number::printNumber()
{
    int i;
    for(i=digits-1;i>=0;i--)
      cout<<str[i]<<" ";
     cout<<endl;
}

int main()
{
    Number n1(255);
    Number n2(254,16);
    n1.printNumber();
    n2.printNumber();
    std::cout << "Press ENTER to continue...";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );
    return 0;
}
#include <iomanip>
#include <iostream>
std::cout << std::hex << number;

int str[80];成员更改为char str[80]。然后将convert()方法内的行str[icount]=m;更改为:str[icount]="0123456789abcdef"[m];

最后,确保str以零结尾,并简单地打印为字符串。

显然,只打印一个十六进制值,你可以按照clcto的建议使用标准库,但我想这不是你的议程。。。

如果您想真正控制输出的格式,请使用旧的C样式printf()。虽然它的语法不如C++流直观,但它更适合做复杂的事情。在十六进制数字的情况下,您将使用x转换:

#include <stdio.h>
int number = 255;
printf("Here is a hex number: %xn", number);

上面的代码将导致的输出

Here is a hex number: ff

现在,如果您想输出数字数据,您经常需要将所有位输出为十六进制,包括前导零。轻松使用printf():

printf("My int has the bits: 0x%08xn", number);

将输出

My int has the bits: 0x000000ff