C: How to save the result of 2 32 bit unsigned integer into a signed integer -


i have following piece of code saves result in 32 bit signed integer , 64 bit signed integer.

using 32 bit signed integer results in problem when subtract 0 2147483647 (max allowed value signed 32 bit integer) correct way should using 64 bit signed integer , should have typecast unsigned 32 bit signed 64 bit desired answer. right way it?

#include <stdio.h> #include <string.h> #include <stdint.h>  int main(void) {     int32_t fig32;     int64_t fig64;     uint32_t peak_seq = 2480694779;     uint32_t pkt_seq = 2480694780;     uint32_t zero_seq = 0;      fig32 = peak_seq - pkt_seq;     fig64 = peak_seq - pkt_seq;      printf("\n 32 ans : %d, 64 ans %ld\n", fig32, fig64);      fig32 = zero_seq - pkt_seq;     fig64 = zero_seq - pkt_seq;      printf("\n 32 ans : %d, 64 ans %ld\n", fig32, fig64);      fig64 = (int64_t)peak_seq - (int64_t)pkt_seq;     printf("\n fix (peak - pkt) 64 ans %ld\n", fig64);      fig64 = (int64_t)zero_seq - (int64_t)pkt_seq;     printf("\n fix (zero - pkt) 64 ans %ld\n", fig64); } 

when run program, following output

 32 ans : -1, 64 ans 4294967295   32 ans : 1814272516, 64 ans 1814272516   fix (peak - pkt) 64 ans -1   fix (zero - pkt) 64 ans -2480694780 
  1. in first line why answer 64 bit 4294967295 , not -1 ?
  2. is typecasting unsigned 32 bit integers signed 64 bit way solve problem?

first of all, in c expression x = y + z; types used calculation of y + z has nothing type of x. type used in calculation depends on types of operands of specific operator.

in case, type used calculate peak_seq - pkt_seq has no relation happen store result. since both operands of type uint32_t (and since int not larger 32 bits on machine), operation carried out on uint32_t type. result of type uint32_t.

since both operands of operation of unsigned type, underflows 4294967295. result of peak_seq - pkt_seq in code (uint32_t)4294967295, or if 0xffffffff.

in first line why answer 64 bit 4294967295 , not -1 ?

when try store result int32_t, gets converted according implementation-defined behavior, in case you'll two's complement version of 0xffffffff -1.

but when try restore result in int64_t, fits fine , value isn't changed.

is typecasting unsigned 32 bit integers signed 64 bit way solve problem?

if want signed numbers, use signed numbers. reason why find results of code strange, if somehow incorrectly expect 2 unsigned operands give signed result.

as side note, when printing int32_t should use printf("%" prid, fig32) , int64_t use prid64 (inttypes.h).


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -