data type conversion - Arithmetically simulate 32-bit integer overflow -
is there way arithmetically simulate 32-bit, twos-complement integer overflow numbers of type value space strict superset of of 32-bit twos-complement integers? need perform such operation in, example, wolframalpha, has no explicit typing , no type casting.
the output of desired convertto32bitsignedint(avalue) function needs same if had cast value in language supports it, such java: (int)avalue.
by example, output of convertto32bitsignedint(17643225600) needs 463356416, same had used next cast (int)17643225600.
for moment, convertto32bitsignedint function (in pseudo code) looks , pretty sure it's not improve solution.
if(x > 2147483647 && floor(x / 2147483647 ) == 1){ homecoming (x - 2*2147483648); }else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 == 0)){ homecoming -1 * (x / 2147483647); }else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 > 0)){ homecoming -1 * ((x - 2147483647) / 2147483647) + 2147483647; }else if(x > 2147483647 && (x % 2147483647 > 0) && (x % 2 == 0)){ homecoming -1 * floor(x / 2147483647) + (x % 2147483647); } //... use case:
i seek demonstrate behavior occures when there 32-bit signed integer overflow in java programme using recursive implementation of factorial function.
public int factorial(int n) { homecoming n == 1 || n==0 ? 1 : n * factorial(n - 1); } this int implementation, factorial(13) gives 1932053504, because 13 * 479001600 > 2147483647, 32-bit signed integer maximum value.
i utilize wolframalpha demonstration. wolframalpha allows numbers > 2147483647 , want simulate these number 32-bit integer numbers. wolframalpha gives real reply 6227020800. able convert 6227020800 1932053504.
edit: rip & replace of initial answer
you can this:
convertto32bitsignedint(avalue) { bits32 = bitand(avalue, bitshiftleft(1, 32) - 1); sign = bitshiftright(bits32, 31); homecoming bits32 - bitshiftleft(sign, 32); } data-type-conversion wolframalpha
No comments:
Post a Comment