Thursday, July 15, 2010

Bitmanipulation with integer64

Take care on bit shifting if the result should be a 64 bit integer. Fragments like the follow code example does not take the obviously desired effect:
int64 i64 = 1 << 32; // move the very right positive bit just 32 ranks to the left
The result on that will be 0. The problem comes up with the return value from the operation 1 << 32, it's an 32 bit integer, even the result will be copied in a 64 bit integer (the bit shfiting operation is executed encapsulated before copy to variable i64). The base operand sets the type of result, in our code it's a constant number (1). And because 1 is a 32 bit integer, the results represents a 32 bit integer too. But why it ends with zero result? Its the reaction for the overflow when trying to access a bit area which is not available on a 32 bit integer (a 32 bit integer has just its 32 bits - not more, not less). Other programming languages reacts in the same situation with exceptions type overflow (f.ex. VB6) or moves the bits in circle (f.ex. C#), but AX quits that problem situation just with a type specified null value.

To ensure the code works fine, do it that way:
int64 base = 1;
int64 result = base << 32; // move the very right positive bit just 32 ranks to the left

No comments:

Post a Comment