bits.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Copyright 2007 nVidia, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  5. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
  6. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7. See the License for the specific language governing permissions and limitations under the License.
  8. */
  9. #ifndef _ZOH_BITS_H
  10. #define _ZOH_BITS_H
  11. // read/write a bitstream
  12. #include "nvcore/debug.h"
  13. namespace ZOH {
  14. class Bits
  15. {
  16. public:
  17. Bits(char *data, int maxdatabits) { nvAssert (data && maxdatabits > 0); bptr = bend = 0; bits = data; maxbits = maxdatabits; readonly = 0;}
  18. Bits(const char *data, int availdatabits) { nvAssert (data && availdatabits > 0); bptr = 0; bend = availdatabits; cbits = data; maxbits = availdatabits; readonly = 1;}
  19. void write(int value, int nbits) {
  20. nvAssert (nbits >= 0 && nbits < 32);
  21. nvAssert (sizeof(int)>= 4);
  22. for (int i=0; i<nbits; ++i)
  23. writeone(value>>i);
  24. }
  25. int read(int nbits) {
  26. nvAssert (nbits >= 0 && nbits < 32);
  27. nvAssert (sizeof(int)>= 4);
  28. int out = 0;
  29. for (int i=0; i<nbits; ++i)
  30. out |= readone() << i;
  31. return out;
  32. }
  33. int getptr() { return bptr; }
  34. void setptr(int ptr) { nvAssert (ptr >= 0 && ptr < maxbits); bptr = ptr; }
  35. int getsize() { return bend; }
  36. private:
  37. int bptr; // next bit to read
  38. int bend; // last written bit + 1
  39. char *bits; // ptr to user bit stream
  40. const char *cbits; // ptr to const user bit stream
  41. int maxbits; // max size of user bit stream
  42. char readonly; // 1 if this is a read-only stream
  43. int readone() {
  44. nvAssert (bptr < bend);
  45. if (bptr >= bend) return 0;
  46. int bit = (readonly ? cbits[bptr>>3] : bits[bptr>>3]) & (1 << (bptr & 7));
  47. ++bptr;
  48. return bit != 0;
  49. }
  50. void writeone(int bit) {
  51. nvAssert (!readonly); // "Writing a read-only bit stream"
  52. nvAssert (bptr < maxbits);
  53. if (bptr >= maxbits) return;
  54. if (bit&1)
  55. bits[bptr>>3] |= 1 << (bptr & 7);
  56. else
  57. bits[bptr>>3] &= ~(1 << (bptr & 7));
  58. if (bptr++ >= bend) bend = bptr;
  59. }
  60. };
  61. }
  62. #endif