From: Holger Schemel Date: Wed, 17 May 2023 10:29:18 +0000 (+0200) Subject: moved code to count bits to separate function X-Git-Tag: 4.3.6.0~14 X-Git-Url: https://git.artsoft.org/?a=commitdiff_plain;h=7078f3af87a1898999f8e2bbfef6c3895d5f7316;p=rocksndiamonds.git moved code to count bits to separate function --- diff --git a/src/editor.c b/src/editor.c index d4e2bc8e..25edbb4b 100644 --- a/src/editor.c +++ b/src/editor.c @@ -12054,19 +12054,10 @@ static boolean isHiresDrawElement(int element) static int numHiresTiles(int element) { - if (!IS_MM_WALL(element)) - return 1; - - int bits = MM_WALL_BITS(element); - int num_bits = 0; - - while (bits) - { - bits &= bits - 1; - num_bits++; - } + if (IS_MM_WALL(element)) + return get_number_of_bits(MM_WALL_BITS(element)); - return num_bits; + return 1; } static void SetDrawModeHiRes(int element) diff --git a/src/libgame/misc.c b/src/libgame/misc.c index a76bba56..02358aa2 100644 --- a/src/libgame/misc.c +++ b/src/libgame/misc.c @@ -1682,6 +1682,31 @@ void swap_number_pairs(int *x1, int *y1, int *x2, int *y2) *y2 = help_y; } +int get_number_of_bits(int bits) +{ + /* + Counting bits set, Brian Kernighan's way + + Brian Kernighan's method goes through as many iterations as there are set + bits. So if we have a 32-bit word with only the high bit set, then it will + only go once through the loop. + + Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan + and Dennis M. Ritchie) mentions this in exercise 2-9. + First published by Peter Wegner in CACM 3 (1960), 322. + */ + + int num_bits = 0; + + while (bits) + { + bits &= bits - 1; // clear the least significant bit set + num_bits++; + } + + return num_bits; +} + /* the "put" variants of the following file access functions check for the file pointer being != NULL and return the number of bytes they have or would have written; this allows for chunk writing functions to first determine the size diff --git a/src/libgame/misc.h b/src/libgame/misc.h index c8e00c84..7097e968 100644 --- a/src/libgame/misc.h +++ b/src/libgame/misc.h @@ -203,6 +203,7 @@ void clear_mem(void *, unsigned int); void swap_numbers(int *, int *); void swap_number_pairs(int *, int *, int *, int *); +int get_number_of_bits(int); int getFile8BitInteger(File *); int putFile8BitInteger(FILE *, int);