简体   繁体   中英

uint32_t is having a negative value when MSB is 1

I need to make a signed value into an unsigned value and while trying to get this to work I found uint32_t is somehow signed when i assign the MSB to 1.

In this code i show what i mean. Test1/2 are to show this isn't only a printf problem, but arimethics aswell.

    #include <stdio.h>
    #include <inttypes.h>

     void main() {
        int reg1S = 0xfffffff4;
        int reg2S = 0xfffffff2;
              
        uint32_t reg1U = 0xfffffff4;
        uint32_t reg2U = 0xfffffff2;

        uint8_t test1,test2;

        test1 = (reg1S < reg2S ? 1:0);                      
        test2 = (reg1U < reg2U ? 1:0); 

        printf("signed = %d \t",test1);
        printf("unsigned = %d \n", test2);
        printf("reg1S= %d \t", reg1S);
        printf("reg1U= %d \n", reg1U);
        printf("reg2S= %d \t", reg2S);
        printf("reg2U= %d \n", reg2U);
     }

this is what the code outputs

signed = 0  unsigned = 0 
reg1S= -12  reg1U= -12 
reg2S= -14  reg2U= -14

note: it doesnt do this with 8 or 16 bit unsigned ints, only 32 and 64 bit

%d is for printing signed types. To print unsigned types, use %u .

Also, types smaller than int will be promoted to that type when passed to printf which is why you don't see this behavior with those types.

Use the correct formats for fixed size integers:

#include <stdio.h>
#include <inttypes.h>

 void main() {
    int32_t reg1S = 0xfffffff4;
    int32_t reg2S = 0xfffffff2;
          
    uint32_t reg1U = 0xfffffff4;
    uint32_t reg2U = 0xfffffff2;

    printf("reg1S= %"PRIi32" \t", reg1S);
    printf("reg1U= %"PRIu32" \n", reg1U);
    printf("reg2S= %"PRIi32" \t", reg2S);
    printf("reg2U= %"PRIu32" \n", reg2U);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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