From 5141596a694fa5189522351d0684483910b88670 Mon Sep 17 00:00:00 2001 From: Ingo Weinhold Date: Mon, 7 Mar 2005 22:02:50 +0000 Subject: [PATCH] Added ffs(). git-svn-id: file:///srv/svn/repos/haiku/trunk/current@11614 a95241bf-73f2-0310-859d-f6bbb57e9c96 --- headers/posix/string.h | 2 ++ src/kernel/libroot/posix/string/ffs.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 src/kernel/libroot/posix/string/ffs.cpp 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; +}