I have a byte array (byte[16]) with one byte in each cell:
0000000000010010 -> [0][0] ..... [1][0][0][1][0].
How do I get the result with base 2 logic?
I want to get the result : 18
. I use C#.
I have a byte array (byte[16]) with one byte in each cell:
0000000000010010 -> [0][0] ..... [1][0][0][1][0].
How do I get the result with base 2 logic?
I want to get the result : 18
. I use C#.
Should be able to use the following, on the assumption that your byte array is purely 0
s and 1
s), (although if this is the case, a bool[]
would probably be a better choice), and that the most significant bit is the 0th element.
private int BytesToInt(byte[] byteArray)
{
// Start with zero
int result = 0;
foreach (var b in byteArray)
{
// For each item in the array, first left-shift the result one bit
result <<= 1;
// If the byte is non-zero, set the lowest bit in the result
if (b != 0) result |= 1;
}
return result;
}
A little bit-twiddling should do you. A LINQ one-liner:
public static ushort ToUShort( this byte[] buffer )
{
const int ushort_bits = sizeof(ushort) * 8 ;
int bits = ushort_bits - 1 ;
return (ushort) buffer
.Take( ushort_bits )
.Select( b => b != 0 ? 1 : 0 )
.Aggregate(0 , (acc,b) => acc | (b<<(bits--)))
;
}
or the equally succinct (and probably faster):
public static ushort ToUShort( this byte[] buffer )
{
uint acc = 0 ;
int bits = sizeof(ushort) * 8 - 1 ;
int max = sizeof(ushort) * 8 ;
for ( int i = 0 ; i < max ; ++i )
{
acc |= (buffer[i]==0?0u:1u)<<(bits--) ;
}
return (ushort) acc ;
}