1/* 2 * Copyright 2005, Ingo Weinhold, bonefish@users.sf.net. 3 * Distributed under the terms of the MIT License. 4 */ 5 6#include <strings.h> 7 8// find first (least significant) set bit 9int 10ffs(int value) 11{ 12 if (!value) 13 return 0; 14 15 // ToDo: This can certainly be optimized (e.g. by binary search). Or not 16 // unlikely there's a single assembler instruction... 17 for (int i = 1; i <= (int)sizeof(value) * 8; i++, value >>= 1) { 18 if (value & 1) 19 return i; 20 } 21 22 // never gets here 23 return 0; 24} 25