[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: bug in ceillog2 macro (Lua-5.1.4)
- From: Leo Razoumov <slonik.az@...>
- Date: Fri, 7 Jan 2011 09:41:38 -0500
Hi List,
In Lua-5.1.4 macro
#define ceillog2(x) (luaO_log2((x)-1) + 1)
gives wrong answer when x is 0.
ceillog2(0) => 32 (should be 1).
I attached below a standalone code snippet to demonstrate the problem.
I use Lua-5.1.4 on Ubuntu-9.04 x86 (32 bits).
There are several ways to fix it and I like _none_ of them.
(1) Ignore the bug. Just make sure that x>0 always.
(2) Convert luaO_log2 (unsigned int x) to signed int and use "if"
statement for negative arguments inside it.
(3) Put if statement into the ceillog2 macro using temp. variable and
GCC extension that allows statements inside expressions (GCC specific
and not C89)
I am leaning towards (2).
--Leo--
/* Notice that ceillog2(0) => 32 */
#include<stdio.h>
#define ceillog2(x) (luaO_log2((x)-1) + 1)
typedef unsigned char lu_byte;
int luaO_log2 (unsigned int x) {
static const lu_byte log_2[256] = {
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
int l = -1;
while (x >= 256) { l += 8; x >>= 8; }
return l + log_2[x];
}
void print(int x){ printf("ceillog2(%d) = %d\n", x, ceillog2(x)); }
int main()
{
print(0);
print(1);
print(2);
return 0;
}
/*EoF*/