c# - Byte[] to BitArray and back to Byte[] -
as title states, i'm trying convert byte array bit array byte array again.
i aware array.copyto()
takes care of byte array received not same original 1 due how bitarray stores values in lsb.
how go in c#?
this should it
static byte[] converttobyte(bitarray bits) { // make sure have enough space allocated when number of bits not multiple of 8 var bytes = new byte[(bits.length - 1) / 8 + 1]; bits.copyto(bytes, 0); return bytes; }
you can verify using simple driver program below
// test make sure works static void main(string[] args) { var bytes = new byte[] { 10, 12, 200, 255, 0 }; var bits = new bitarray(bytes); var newbytes = converttobyte(bits); if (bytes.sequenceequal(newbytes)) console.writeline("successfully converted byte[] bits , byte[]"); else console.writeline("conversion problem"); }
i know op aware of array.copyto
solution (which similar have here), don't see why causing bit order issues. fyi, using .net 4.5.2 verify it. , hence have provided test case confirm results
Comments
Post a Comment