C++使数字以十六进制显示
C++ make numbers appear in hexadecimal
我想让一个数字出现在十六进制字母表中,但我不知道怎么做。
例如,我使用了数字我想把号码显示为"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
相关文章:
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- 'cout'将整数显示为十六进制
- 如何在不将其转换为 ASCII 字符的情况下显示 QByteArray 的十六进制值
- 当Cppunit断言失败时,如何显示十六进制值
- 在c++中创建和显示十六进制字符串
- 如何附加到相邻的十六进制值,然后显示
- 如何在单个块中显示十六进制值
- 如何在不显示十六进制的情况下读取dat文件中的文本?C++
- C++.将二进制文件读入缓冲区后,如何以十六进制显示缓冲区
- 为什么该函数以相反的顺序显示十六进制代码
- GDB:显示函数将我的 {type} 的地址打印为整数——想改成十六进制
- 如何获取显示字节十六进制值的字符串
- 在消息中显示每个字符的十六进制
- 为什么无符号字符不能正确显示十六进制值
- 如何用十六进制而不是ASCII符号显示实际值?
- 使用哪个小部件将硬盘扇区显示为十六进制
- 我怎么能阻止我的整数显示为十六进制
- 十六进制转储实用程序c++显示十六进制和Ascii
- C++使数字以十六进制显示