c# - Why I can't convert a byte[2] array to int with BitConverter? -


the main problem recive binary number 10 bits in use serialport use receive complete data:

byte[] buf = new byte[2]; serialport.read(buf, 0, buf.length); bitarray bits = new bitarray(buf); 

the original idea convert binary int this:

foreach (bool b in bits) {     if(b){         binary += "1";     }     else{         binary+= "0";     } }  decimal = convert.toint32(binary, 2);  decimal = decimal >> 6; 

binary string, works need know if exists solution, instead of previuos code try this:

decimal = bitconverter.toint16(buf, 0); 

but read first 8 bits, need other 2 bits missing! if change toint16 toint32

decimal = bitconverter.toint32(buf, 0); 

the program stops system.argumentexception: destination array not long enough...

what can do?

you can shift values in bytes match, , put them together. if got use of bits right, be:

int value = (buf[0] << 2) | (buf[1] >> 6); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -