]> git.codecow.com Git - Monocypher.git/commitdiff
Remove unnecessary dependency on 2's complement
authorMichael Forney <mforney@mforney.org>
Tue, 19 Nov 2019 20:15:16 +0000 (12:15 -0800)
committerMichael Forney <mforney@mforney.org>
Tue, 19 Nov 2019 20:15:16 +0000 (12:15 -0800)
Although the bit-representation of signed integer types in C99 is
implementation-defined and can be sign-magnitude, one's complement, or
two's complement[0], the conversion of negative values to an unsigned
integer type is defined to be adding 1 plus the maximum value of the
unsigned type[1].

Since -1 + 0xffffffff + 1 == 0xffffffff, just using u32 here has the
right behavior without relying on the representation of signed integers.

[0] http://port70.net/~nsz/c/c99/n1256.html#6.2.6.2p2
[1] http://port70.net/~nsz/c/c99/n1256.html#6.3.1.3p2

src/monocypher.c

index d9b6cfba5bf7ad762d41c524fd187ce0d2fbec03..5855ec09f42d10b232a952ef6e5f4d57017a32e6 100644 (file)
@@ -1029,7 +1029,7 @@ static void fe_sub (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] - g[i];}
 
 static void fe_cswap(fe f, fe g, int b)
 {
-    i32 mask = -b; // rely on 2's complement: -1 = 0xffffffff
+    u32 mask = -b; // -1 = 0xffffffff
     FOR (i, 0, 10) {
         i32 x = (f[i] ^ g[i]) & mask;
         f[i] = f[i] ^ x;
@@ -1039,7 +1039,7 @@ static void fe_cswap(fe f, fe g, int b)
 
 static void fe_ccopy(fe f, const fe g, int b)
 {
-    i32 mask = -b; // rely on 2's complement: -1 = 0xffffffff
+    u32 mask = -b; // -1 = 0xffffffff
     FOR (i, 0, 10) {
         i32 x = (f[i] ^ g[i]) & mask;
         f[i] = f[i] ^ x;