From 37f9058c4d39e111d534b1ad5b214dce703fbbc3 Mon Sep 17 00:00:00 2001 From: Olaf Bergmann Date: Wed, 1 Jun 2011 18:10:34 +0200 Subject: [PATCH] Helper functions for bit-vector manipulation. These functions are supposed to work on 8-bit machines. --- bits.h | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 bits.h diff --git a/bits.h b/bits.h new file mode 100644 index 00000000..f984fc99 --- /dev/null +++ b/bits.h @@ -0,0 +1,78 @@ +/* + * bits.h -- bit vector manipulation + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file bits.h + * @brief bit vector manipulation + */ + +#ifndef _BITS_H_ +#define _BITS_H_ + +#include + +/** + * Sets the bit @p bit in bit-vector @p vec. This function returns @c + * 1 if bit was set or @c 0 on error (i.e. when the given bit does + * not fit in the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to set in @p vec. + * + * @return @c 0 if @p bit does not fit into @p vec, @c 1 otherwise. + */ +inline static int +bits_setb(uint8_t *vec, size_t size, uint8_t bit) { + if (size < (bit >> 3)) + return 0; + + *(vec + (bit >> 3)) |= 1 << ((bit & 0x07) - 1); + return 1; +} + +/** + * Clears the bit @p bit from bit-vector @p vec. This function returns + * @c 1 if bit was cleared or @c 0 on error (i.e. when the given bit + * does not fit in the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to clear from @p vec. + * + * @return @c 0 if @p bit does not fit into @p vec, @c 1 otherwise. + */ +inline static int +bits_clrb(uint8_t *vec, size_t size, uint8_t bit) { + if (size < (bit >> 3)) + return 0; + + *(vec + (bit >> 3)) &= ~(1 << ((bit & 0x07) - 1)); + return 1; +} + +/** + * Gets the status of bit @p bit from bit-vector @p vec. This function returns + * @c 1 if the bit is set, @c 0 otherwise (even in case of an error).. + * + * @param vec The bit-vector to read from.. + * @param size The size of @p vec in bytes. + * @param bit The bit to get from @p vec. + * + * @return @c 1 if the bit is set, @c 0 otherwise. + */ +inline static int +bits_getb(const uint8_t *vec, size_t size, uint8_t bit) { + if (size < (bit >> 3)) + return 0; + + return (*(vec + (bit >> 3)) & (1 << ((bit & 0x07) - 1))) != 0; +} + +#endif /* _BITS_H_ */