如何加上十六进制(无输出)?
How to plus hex( No output)?
我的代码:
#include <iostream>
using namespace std;
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
cout << c;
}
现在
c = 11
我想要这个:
c = 000B
我该怎么办?
据我了解,您希望以十六进制特定格式检索结果 XXXX
。
计算加法与任何数基相同,您只需要使用(这里我显示)您格式的结果。
您可以这样做,例如:
#include <iostream>
#include <iomanip>
std::string displayInPersonalizedHexa(unsigned int a)
{
std::stringstream ss;
ss << std::uppercase<< std::setfill('0') << std::setw(4) << std::hex<< a;
std::string x;
ss >>x;
//std::cout << x;
return x;
}
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
// displays 000B
std::cout << displayInPersonalizedHexa(c) << std::endl;
// adds c=c+1
c=c+1;
// displays 000C
std::cout << displayInPersonalizedHexa(c) << std::endl;
//0xC+5 = 0x11
c=c+5;
// displays 0011
std::cout << displayInPersonalizedHexa(c) << std::endl;
}
这将输出
000B
000C
0011
当你这样做时
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
}
则c
有11
的值,它也有0x000B
的值。它在使用 11
作为基础的表示中也具有 10
的值。
11
和 0x000B
(以及 10
)是同一值的不同表示。
当您使用 std::cout
时,该数字默认打印为十进制。您选择在屏幕上打印值的表示方式对 c
.
的实际值没有任何影响
我的代码:
#include <iostream>
using namespace std;
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
cout << c;
}
现在
c = 11
我想要这个:
c = 000B
我该怎么办?
据我了解,您希望以十六进制特定格式检索结果 XXXX
。
计算加法与任何数基相同,您只需要使用(这里我显示)您格式的结果。
您可以这样做,例如:
#include <iostream>
#include <iomanip>
std::string displayInPersonalizedHexa(unsigned int a)
{
std::stringstream ss;
ss << std::uppercase<< std::setfill('0') << std::setw(4) << std::hex<< a;
std::string x;
ss >>x;
//std::cout << x;
return x;
}
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
// displays 000B
std::cout << displayInPersonalizedHexa(c) << std::endl;
// adds c=c+1
c=c+1;
// displays 000C
std::cout << displayInPersonalizedHexa(c) << std::endl;
//0xC+5 = 0x11
c=c+5;
// displays 0011
std::cout << displayInPersonalizedHexa(c) << std::endl;
}
这将输出
000B
000C
0011
当你这样做时
int main() {
unsigned int a = 0x0009, b = 0x0002;
unsigned int c = a + b;
}
则c
有11
的值,它也有0x000B
的值。它在使用 11
作为基础的表示中也具有 10
的值。
11
和 0x000B
(以及 10
)是同一值的不同表示。
当您使用 std::cout
时,该数字默认打印为十进制。您选择在屏幕上打印值的表示方式对 c
.