bits.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2013 Swift Navigation Inc.
00003  * Contact: Fergus Noble <fergus@swift-nav.com>
00004  *
00005  * This source is subject to the license found in the file 'LICENSE' which must
00006  * be be distributed together with this source. All other rights reserved.
00007  *
00008  * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
00009  * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
00010  * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
00011  */
00012 
00013 #include "bits.h"
00014 
00027 u32 getbitu(const u8 *buff, u32 pos, u8 len)
00028 {
00029     u32 bits = 0;
00030 
00031     for (u32 i = pos; i < pos + len; i++) {
00032       bits = (bits << 1) +
00033              ((buff[i/8] >> (7 - i%8)) & 1u);
00034     }
00035 
00036     return bits;
00037 }
00038 
00049 s32 getbits(const u8 *buff, u32 pos, u8 len)
00050 {
00051     s32 bits = (s32)getbitu(buff, pos, len);
00052 
00053     /* Sign extend, taken from:
00054      * http://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend
00055      */
00056     s32 m = 1u << (len - 1);
00057     return (bits ^ m) - m;
00058 }
00059 
00068 void setbitu(u8 *buff, u32 pos, u32 len, u32 data)
00069 {
00070   u32 mask = 1u << (len - 1);
00071 
00072   if (len <= 0 || 32 < len)
00073     return;
00074 
00075   for (u32 i = pos; i < pos + len; i++, mask >>= 1) {
00076     if (data & mask)
00077       buff[i/8] |= 1u << (7 - i % 8);
00078     else
00079       buff[i/8] &= ~(1u << (7 - i % 8));
00080   }
00081 }
00082 
00091 void setbits(u8 *buff, u32 pos, u32 len, s32 data)
00092 {
00093   setbitu(buff, pos, len, (u32)data);
00094 }
00095 


swiftnav
Author(s):
autogenerated on Sat Jun 8 2019 18:55:14