parsing - C# parse non uniform bit sequences from array of bytes -


question: there more efficient way parse bits out of byte array integer values? if so, be?

data read off stream packet consisting of series of bytes (which held in byte array). data compressed in these bytes such value may spread across multiple bytes (in sequence). bits making values vary in size depending on "type" of packet (which held in first 5 bits (starting msb) of first byte. e.g.,

byte[] bytes = {0x73, 0xa4}; // yields: 0111001110100100 // vals:   [ 1 ][  2  ]3[4] 

currently use extension method:

public static string converttobinarystring(this byte[] bytes) {     return string.join("", bytes.select(x => convert.tostring(x, 2).padleft(8, '0'))); } 

to convert byte array binary string. use 1 of these 2 extension methods convert binary string int or array of int:

static readonly regex isbinary = new regex("^[01]{1,32}$", regexoptions.compiled); public static bool tryparsebits(this string toparse, int start, int length, out int intval) {     intval = -1;     if (!isbinary.ismatch(toparse)) return false;     if ((start + length + 1) > toparse.length) return false;     intval = convert.toint32(toparse.substring(start, length), 2);     return true; } public static bool tryparsebits(this string toparse, queue<int> lengths, out list<int> vals) {     vals = new list<int>();     if (!isbinary.ismatch(toparse)) return false;     var idx = 0;     while (lengths.count > 0)     {         var l = lengths.dequeue();         if ((idx + l) > toparse.length) return false;         vals.add(convert.toint32(toparse.substring(idx, l), 2));         idx += l;     }     return true; } 

example use:

int type; var success = "0111001110100100".tryparsebits(0, 5, out type); 

results in type = 14

background: stream being read can deliver 12 packets/second. there preprocessing occurs prior having parse bytes , there significant post processing occurs on values. data packets split across 4 threads using parallel.foreach. values never greater 28 bits don't worry sign bit when converting int.

have tried bitmask?
knowing eg last 4 bits of first bytearray our first val can do:

byte[] bytes = { 0x73, 0xa4 }; int v1 = bytes[0] & 0x0f; //second val: int v2 = bytes[2] & 0xf0; 

or
before applying mask store in lager nr.

 int total = 0;  total = total | bytes[0];  total = total << 8;  total = total | bytes[1];  //now 2 bytes array stored in number in our case total be: 111001110100100  //after storing apply bit masks described above:  // last 3 bytes  int var1 = total & 0x7 //mask last 3 bytes  total = total >> 3; //take out last 3 bytes  int var2 = total & 0x1 //last byte.  total = total >>1;  //and on 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -