2013-11-27 16:28:31 +01:00
|
|
|
/*
|
2013-06-18 17:21:38 +02:00
|
|
|
* Copyright (C) 2013 Freie Universität Berlin
|
2010-09-22 15:10:42 +02:00
|
|
|
*
|
2014-07-31 19:45:27 +02:00
|
|
|
* This file is subject to the terms and conditions of the GNU Lesser
|
|
|
|
* General Public License v2.1. See the file LICENSE in the top level
|
|
|
|
* directory for more details.
|
2013-11-27 16:28:31 +01:00
|
|
|
*/
|
2014-02-11 18:15:43 +01:00
|
|
|
|
2013-11-27 16:28:31 +01:00
|
|
|
/**
|
|
|
|
* @ingroup core_util
|
|
|
|
* @{
|
|
|
|
*
|
|
|
|
* @file bitarithm.c
|
|
|
|
* @brief Bit arithmetic helper functions implementation
|
|
|
|
*
|
2014-01-28 11:50:12 +01:00
|
|
|
* @author Kaspar Schleiser <kaspar@schleiser.de>
|
2013-11-27 16:28:31 +01:00
|
|
|
* @author Martin Lenders <mlenders@inf.fu-berlin.de>
|
2014-05-20 00:43:43 +02:00
|
|
|
* @author René Kijewski <rene.kijewski@fu-berlin.de>
|
2010-09-22 15:10:42 +02:00
|
|
|
*
|
2013-11-27 16:28:31 +01:00
|
|
|
* @}
|
2010-09-22 15:10:42 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
2014-05-20 00:43:43 +02:00
|
|
|
#include "bitarithm.h"
|
|
|
|
|
2014-04-10 22:28:35 +02:00
|
|
|
unsigned bitarithm_msb(unsigned v)
|
2010-09-22 15:10:42 +02:00
|
|
|
{
|
2014-05-20 00:43:43 +02:00
|
|
|
if ((signed) v >= 0) {
|
|
|
|
v &= -v;
|
|
|
|
return bitarithm_lsb(v);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return sizeof (v) * 8 - 1;
|
2013-06-20 18:18:29 +02:00
|
|
|
}
|
2010-09-22 15:10:42 +02:00
|
|
|
}
|
2013-12-09 22:44:53 +01:00
|
|
|
|
2014-05-20 00:43:43 +02:00
|
|
|
unsigned bitarithm_lsb(unsigned v)
|
|
|
|
{
|
|
|
|
unsigned r = 0;
|
|
|
|
while ((v & 1) == 0) {
|
2013-12-09 22:44:53 +01:00
|
|
|
v >>= 1;
|
|
|
|
r++;
|
2014-05-20 00:43:43 +02:00
|
|
|
}
|
2013-12-09 22:44:53 +01:00
|
|
|
return r;
|
|
|
|
}
|
2014-05-20 00:43:43 +02:00
|
|
|
|
2014-04-10 22:28:35 +02:00
|
|
|
unsigned bitarithm_bits_set(unsigned v)
|
2013-12-09 22:44:53 +01:00
|
|
|
{
|
|
|
|
unsigned c; // c accumulates the total bits set in v
|
|
|
|
|
|
|
|
for (c = 0; v; c++) {
|
|
|
|
v &= v - 1; // clear the least significant bit set
|
|
|
|
}
|
|
|
|
|
|
|
|
return c;
|
|
|
|
}
|