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
CodePudding user response:
%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.
CodePudding user response:
Use the correct formats for fixed size integers:
#include <stdio.h>
#include <inttypes.h>
void main() {
int32_t reg1S = 0xfffffff4; \\ <- implementation defined
int32_t reg2S = 0xfffffff2; \\ <- implementation defined
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);
}