S
Spoon
Consider the following program:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
uint32_t a = strtoul(argv[1], 0, 0);
uint32_t b = strtoul(argv[2], 0, 0);
double d = a-b;
printf("%f\n", d);
return 0;
}
$ ./a.out 5 6
4294967295.000000
This is what I expected.
Since a-b would be negative, the result is a-b+2^32.
However, if I replace uint32_t with uint16_t:
$ ./a.out 5 6
-1.000000
I expected 65535 (-1+2^16).
I suppose I'm forgetting some integer promotion rule?
Is the simple fix just to write:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
uint16_t a = strtoul(argv[1], 0, 0);
uint16_t b = strtoul(argv[2], 0, 0);
uint16_t diff = a-b;
double d = diff;
printf("%f\n", d);
return 0;
}
Regards.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
uint32_t a = strtoul(argv[1], 0, 0);
uint32_t b = strtoul(argv[2], 0, 0);
double d = a-b;
printf("%f\n", d);
return 0;
}
$ ./a.out 5 6
4294967295.000000
This is what I expected.
Since a-b would be negative, the result is a-b+2^32.
However, if I replace uint32_t with uint16_t:
$ ./a.out 5 6
-1.000000
I expected 65535 (-1+2^16).
I suppose I'm forgetting some integer promotion rule?
Is the simple fix just to write:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
uint16_t a = strtoul(argv[1], 0, 0);
uint16_t b = strtoul(argv[2], 0, 0);
uint16_t diff = a-b;
double d = diff;
printf("%f\n", d);
return 0;
}
Regards.