[英]How to print hex from uint32_t?
The code I have been working on requires that I print a variable of type uint32_t
in hexadecimal, with a padding of 0s and minimum length 8. The code I have been using to do this so far is: 我一直在处理的代码要求我打印一个十六进制的
uint32_t
类型的变量,填充为0,最小长度为8.到目前为止我用来执行此操作的代码是:
printf("%08lx\n",read_word(address));
Where read_word returns type uint32_t. 其中read_word返回类型uint32_t。 I have used jx, llx, etc. formats to no avail, is there a correct format that can be used?
我使用jx,llx等格式无济于事,是否有正确的格式可以使用?
EDIT: 编辑:
I have found the problem lies in what I am passing. 我发现问题在于我正在经历的事情。 The function read_word is returns a value from a uint32_t vector.
函数read_word从uint32_t向量返回一个值。 It seems that this is the problem that is causing problems with out putting hex.
这似乎是导致输出hex的问题。 Is this a passing by reference/value issue and what is the fix?
这是一个通过引用/值问题传递,修复是什么?
read_word function: read_word函数:
uint32_t memory::read_word (uint32_t address) {
if(address>(maxWord)){
return 0;
}
return mem[address];
}
mem deceleration: 记忆减速:
std::vector<uint32_t> mem=decltype(mem)(1024,0);
To do this in C++ you need to abuse both the fill and the width manipulators: 要在C ++中执行此操作,您需要滥用填充和宽度操纵器:
#include <iostream>
#include <iomanip>
#include <cstdint>
int main()
{
uint32_t myInt = 123456;
std::cout << std::setfill('0') << std::setw(8) << std::hex << myInt << '\n';
}
Output 产量
0001e240
For C it gets a little more obtuse. 对于C来说,它会变得更加迟钝。 You use
inttypes.h
你使用
inttypes.h
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main()
{
uint32_t myInt = 123456;
printf("%08" PRIx32 "\n", myInt);
return 0;
}
Output 产量
0001e240
Note that in C, the constants from inttypes.h
are used with the language string-concatenation feature to form the required format specifier. 请注意,在C中,
inttypes.h
中的常量与语言字符串连接功能一起使用,以形成所需的格式说明符。 You only provide the zero-fill and minimum length as a preamble. 您只提供零填充和最小长度作为前导码。
%jx
+ typecast %jx
+ typecast
I think this is correct: 我认为这是正确的:
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint32_t i = 0x123456;
printf("%08jx\n", (uintmax_t)i);
return 0;
}
compile and run: 编译并运行:
gcc -Wall -Wextra -pedantic -std=c99 main.c
./a.out
Output: 输出:
00123456
Let me know if you can produce a failing test case. 如果您能够生成一个失败的测试用例,请告诉我。
Tested in Ubuntu 16.04, GCC 6.4.0. 在Ubuntu 16.04,GCC 6.4.0中测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.