有趣的位运算

Interesting bitwise operation

我今天在审查 SHA1 在 C 中的实现时遇到了一些相当有趣的代码。

temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
temp &= 0xFFFFFFFF;

我觉得有趣的部分是temp &= 0xFFFFFFFF;。请注意,temp 已声明为 无符号整数 。这个操作会不会根本就没有效果?我唯一能想到的是,设计者试图强制使用 32 位整数,但这不会在编译时完成吗?
我很想知道人们的想法。

在某些机器上,int(因此 unsigned int 也是)可能是 64 位类型。掩码在 int 是 32 位类型的机器上是空操作,但在它是 64 位类型的机器上是关键的。编译器会知道并在它没有做任何有用的事情时优化操作。

另外,以前也有36-bit int types and others with 60-bit int types的机器;在这样的机器上也很重要。

SHA1的reference implementation,在评论中有如下说明:

/*
 *  sha1.c
 *
 *  Description:
 *      This file implements the Secure Hashing Algorithm 1 as
 *      defined in FIPS PUB 180-1 published April 17, 1995.
 *
 *      The SHA-1, produces a 160-bit message digest for a given
 *      data stream.  It should take about 2**n steps to find a
 *      message with the same digest as a given message and
 *      2**(n/2) to find any two messages with the same digest,
 *      when n is the digest size in bits.  Therefore, this
 *      algorithm can serve as a means of providing a
 *      "fingerprint" for a message.
 *
 *  Portability Issues:
 *      SHA-1 is defined in terms of 32-bit "words".  This code
 *      uses <stdint.h> (included via "sha1.h" to define 32 and 8
 *      bit unsigned integer types.  If your C compiler does not
 *      support 32 bit unsigned integers, this code is not
 *      appropriate.
 *
 *  Caveats:
 *      SHA-1 is designed to work with messages less than 2^64 bits
 *      long.  Although SHA-1 allows a message digest to be generated
 *      for messages of any number of bits less than 2^64, this
 *      implementation only works with messages with a length that is
 *      a multiple of the size of an 8-bit character.
 *
 */

Portability Issues 是此 SHA1 实现中此操作的情况,它允许它在具有更大 ints 的机器上正常运行。