Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read bit range from byte array

I am looking for a method that will enable me to get a range of bits. For example if I have the binary data

0 1 0 1 1 0 1 1 1 1 0 1 0 1 1 1 (2 bytes)

I might need to get data from range bit 3 to 9. In other words I would be interested in:

0 1 0 1 1 0 1 1 1 1 0 1 0 1 1 1

so in short I will like to construct the method:

 byte[] Read(byte[] data, int left, int right){ 

     // implementation
 }

so that if I pass the data new byte[]{91,215}, 3, 9 I will get byte[]{122} (note byte 91 and 215 = 0 1 0 1 1 0 1 1 1 1 0 1 0 1 1 1 and byte 122 = 1 1 1 1 0 1 0 same binary data as the example.

It would be nice if I could use the << operator on byte arrays such as doing something like:

  byte[] myArray = new byte[] { 1, 2, 3 };
  var shift = myArray << 2;

If you are interested to know why I need this functionality:

I am creating a project on a board and often need to read and write values to the memory. The cdf, sfr, or ddf (refereed to as chip definition file) contains information about a particular chip. That file may look like:

;     Name                            Zone      Address     Bytesize  Displaybase Bitrange
;     ----                            ----      -------     --------  ----------- --------

sfr = "SPI0_CONTROL"              , "Memory", 0x40001000,        4, base=16
sfr = "SPI0_CONTROL.SPH"          , "Memory", 0x40001000,        4, base=16,    bitRange=25-25
sfr = "SPI0_CONTROL.SPO"          , "Memory", 0x40001000,        4, base=16,    bitRange=24-24
sfr = "SPI0_CONTROL.TXRXDFCOUNT"  , "Memory", 0x40001000,        4, base=16,    bitRange=8-23
sfr = "SPI0_CONTROL.INT_TXUR"     , "Memory", 0x40001000,        4, base=16,    bitRange=7-7
sfr = "SPI0_CONTROL.INT_RXOVF"    , "Memory", 0x40001000,        4, base=16,    bitRange=6-6

Since I am reading a lot of variables (sometimes 80 times per second) I will like to have an efficient algorithm. I guess my approach would be that if the bytesize is 8 then I will create a long from those 8 bytes then use the << and >> operators in order to get what I need. if the bytesize if 4 then I will create an int and use the << and >> operators but How will I do it if I need to read 16 bytes though? I guess my question should been how to implement the << and >> operators on custom struct types.

like image 541
Tono Nam Avatar asked Sep 26 '12 19:09

Tono Nam


2 Answers

You need the BitArray class from System.Collections.

like image 80
STO Avatar answered Nov 20 '22 07:11

STO


Looks like you could help a "bit stream". There is an implementation of such a concept here. Take a look, perhaps it fits your needs.

like image 3
Marius Bancila Avatar answered Nov 20 '22 08:11

Marius Bancila