简体   繁体   English

宏打印不正确的输出

[英]The macro prints incorrect output

I'm learning C programming and this is my problem. 我正在学习C编程,这是我的问题。 I feel like I've learned the macro topic in C but I guess I'm not quite ready yet. 我觉得我已经学习了C语言中的宏主题,但我想我还没有准备好。

#define PGSIZE    4096 
#define CONVERT(sz)    (((sz)+PGSIZE-1) & ~(PGSIZE-1))

printf("0x%x", CONVERT(0x123456));

Here is the problem. 这是问题所在。 My expected output is 0x100000000000 but it prints 0x124000 . 我的预期输出是0x100000000000但它输出0x124000

((sz)+PGSIZE-1) = (0x123456)+4096-1 
                = (0x123456)+(0x1000 0000 0000) - 1 //4096 is 2^12
                =  0x1000 0012 3456 - 1
                =  0x1000 0012 3455

~(PGSIZE-1) => ~(0x0111 1111 1111) = 0x1000 0000 0000

((sz)+PGSIZE-1) & ~(PGSIZE-1) = (0x1000 0012 3455) & (0x1000 0000 0000)
                              = 0x100000000000

But when I ran the program, it prints 0x124000. 但是,当我运行该程序时,它将打印0x124000。

What am I doing wrong? 我究竟做错了什么?

You showed in the question: 您显示的问题是:

((sz)+PGSIZE-1) => (0x123456)+4096-1 
                =(0x123456)+(0x1000 0000 0000) - 1 //4096 is 2^12
                =0x1000 0012 3456 - 1

You converted 4096 to a binary notation, but then treat it as a hexadecimal number. 您将4096转换为二进制表示法,然后将其视为十六进制数。 That won't work. 那行不通。 If you want to keep the hexadecimal notation, that's: 如果要保留十六进制表示法,则为:

((sz)+PGSIZE-1) => (0x123456)+4096-1 
                =(0x123456)+(0x1000) - 1
                =0x124456 - 1

Or converting both to binary, that's: 或将它们都转换为二进制,那就是:

((sz)+PGSIZE-1) => (0x123456)+4096-1 
                =(0b1_0010_0011_0100_0101_0110)+(0b1_0000_0000_0000) - 1
                = 0b1_0010_0100_0100_0101_0110 - 1

The error is in your calculation. 该错误在您的计算中。 2^12 is not 1000 0000 0000, but 0001 0000 0000 0000. 2 ^ 12不是1000 0000 0000,而是0001 0000 0000 0000。

The weights of binary begin as 2^0 which is one so 2^12 comes at 13th position so 4096 is 0x1000 If you use this for your manual calculation you will get 0x124000 as your answer. 二进制的权重始于2 ^ 0,即1,因此2 ^ 12位于第13位,因此4096为0x1000如果将其用于手动计算,您将得到0x124000作为答案。

The below calculation also answers your doubt "how 0x124455 & 1000 becomes 0x124000? Does if automatically fill 1s to the front? Could you explain little more about it on the question?" 下面的计算还回答了您的疑问“ 0x124455和1000如何变成0x124000?是否自动在前面填充1s?您能否在这个问题上解释更多?” in the comment of the previous answer. 在先前答案的评论中。

4096 = 0x1000 
4096-1 => 0xfff => 0x0000 0fff
    ~(4096-1) is thus 0xfffff000

    Coming to the addition part in macro 
     (0x123456)+4096-1 
         =>0x123456+0x1000-1
         =>0x124456-1
         =>0x124455

    You result will be 0x124455 & 0xfffff000 which is 0x124000 which is the correct output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM