这个宏如何检测对齐问题?

Ste*_*ven 6 c

我正在跟踪一些关于以下实现的源代码strlen

#include <_ansi.h>
#include <string.h>
#include <limits.h>

#define LBLOCKSIZE   (sizeof (long))
#define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))

#if LONG_MAX == 2147483647L
#define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
#else
#if LONG_MAX == 9223372036854775807L
/* Nonzero if X (a long int) contains a NULL byte. */
#define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
#else
#error long int is not a 32bit or 64bit type.
#endif
#endif

#ifndef DETECTNULL
#error long int is not a 32bit or 64bit byte
#endif

size_t
_DEFUN (strlen, (str),
    _CONST char *str)
{
_CONST char *start = str;

#if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
unsigned long *aligned_addr;

/* Align the pointer, so we can search a word at a time.  */
while (UNALIGNED (str))
    {
    if (!*str)
    return str - start;
    str++;
    }

/* If the string is word-aligned, we can check for the presence of
    a null in each word-sized block.  */
aligned_addr = (unsigned long *)str;
while (!DETECTNULL (*aligned_addr))
    aligned_addr++;

/* Once a null is detected, we check each byte in that block for a
    precise position of the null.  */
str = (char *) aligned_addr;

#endif /* not PREFER_SIZE_OVER_SPEED */

while (*str)
    str++;
return str - start;
}
Run Code Online (Sandbox Code Playgroud)

我能理解大部分代码,但我不知道以下宏如何判断字符串是否按字对齐:

#define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?

sta*_*ark 6

如果LBLOCKSIZE是 2 的幂,LBLOCKSIZE - 1则是低位全 1 的模式。如果该模式中的任何位在地址中设置,则它不会与该块大小对齐。

例子:

LBLOCKSIZE = 4096
LBLOCKSIZE - 1 = 4095 = 0xFFF
Run Code Online (Sandbox Code Playgroud)

通常,磁盘块和内存块的大小是 2 的幂,因为硬件往往更喜欢它们。尽管我们中的一些人已经足够记住十进制机器了。