diff --git a/headers/posix/string.h b/headers/posix/string.h index 0a866812be..802abcd522 100644 --- a/headers/posix/string.h +++ b/headers/posix/string.h @@ -77,6 +77,8 @@ extern const char *strsignal(int signal); #define bcopy(source, dest, length) memcpy((dest), (source), (length)) #define bzero(buffer, length) memset((buffer), 0, (length)) +extern int ffs(int i); + #ifdef __cplusplus } #endif diff --git a/src/kernel/libroot/posix/string/ffs.cpp b/src/kernel/libroot/posix/string/ffs.cpp new file mode 100644 index 0000000000..7f5ff3f6b3 --- /dev/null +++ b/src/kernel/libroot/posix/string/ffs.cpp @@ -0,0 +1,24 @@ +/* + * Copyright 2005, Ingo Weinhold, bonefish@users.sf.net. + * Distributed under the terms of the MIT License. + */ + +#include + +// find first (least significant) set bit +int +ffs(int value) +{ + if (!value) + return 0; + + // ToDo: This can certainly be optimized (e.g. by binary search). Or not + // unlikely there's a single assembler instruction... + for (int i = 1; i <= (int)sizeof(value) * 8; i++, value >>= 1) { + if (value & 1) + return i; + } + + // never gets here + return 0; +}