[erlang-questions] Fix width integer computations
Mikael Pettersson
mikpe@REDACTED
Thu Dec 21 14:49:11 CET 2006
Joe Armstrong writes:
> Question:
>
> I have a C program that has a line of code like this:
>
> mx = (z>>5 ^ y<<2) + (y>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);
>
> All the variables are unsigned long
>
> How do I code this in Erlang?
>
> First thoughts:
>
> transcribe X >> N as trim(X bsl N)
> X << N as trim(X bsr N)
> X + Y as trim(X + Y)
> X ^ Y as X bxor Y
> where trim(X) = X band 16#ffffffff
>
> Is this correct? - The result must be bit identical to the C code,
> how many of the trims can I eliminate?
>
> A nieve translation of (y>>3 ^ z<<4)
>
> is trim(Y bsr 3) bxor trim(Z bsl 4)
>
> identical to trim((Y bsr 3) bxor (Z bsl 4)) ????
- bsl and + may extend the number of bits
- bsr (you defined it as unsigned >>) is sensitive to the number
of bits but does not extend it
- bxor preserves or reduces the number of bits
So your (y>>3) ^ (z<<4) should be (Y bsr 3) bxor trim(Z bsl 4).
/Mikael
More information about the erlang-questions
mailing list