Keep Leading zeros C

依然范特西╮ 提交于 2019-12-04 05:05:06

问题


I am trying to read the memory addresses from /proc//maps and I use the following code

for (ptr = NULL; getline(&ptr, &n, file) > 0;)     {
   if (ptr[0]== ' ') { continue; }
   sscanf(ptr, "%lx-%lx", &r0, &r1);
   printf("r0: %lx, r1: %lx\n", r0, r1);           }

Assume that file points to /proc//maps & ptr is the line pointer. But when you consider a maps file, it doesn't read the file proper. It drops the zero, it does not pick the zeros up. So consider:

00110000-00123000 r-xp 00000000 08:01 129925     /lib/i686/cmov/libnsl-2.11.1.so

After running through my program:

r0: 110000, r1: 123000

How I keep the leading zeros to output something like this:

r0: 00110000, r1: 00123000

Edit: The printf is for debugging.

Here is what I do with r1 later on

mem = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, mem_fd, r1)

回答1:


You're reading these values into integers; integers don't have leading zeros.

If you know how many digits you want to pad out the length to, you can specify that in your format string:

printf("r0: %08lx, r1: %08lx\n", r0, r1);

There's no way to store and recall the exact number of leading zeroes without storing the value in a different format (e.g, a string), though.




回答2:


Use the 0 flag (which specifies leading zeros), followed by the padded length.

printf("r0: %08lx, r1: %08lx\n", r0, r1);
             ^^         ^^

This link is a good reference to look at.



来源:https://stackoverflow.com/questions/8538963/keep-leading-zeros-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!