Convert a string into a byte array in c# -


i have string,

string var="11001100"  

i want convert byte array.

barray[0]=0x00; barray[1]=0x00; barray[2]=0x01; barray[3]=0x01; barray[4]=0x00; barray[5]=0x00; barray[6]=0x01; barray[7]=0x01; 

can guide me in this? tried following code, data in ascii. not want that.

barray = encoding.default.getbytes(var); 

i suggest using linq:

using system.linq;  ...  string var = "11001100";  byte[] barray = var   .select(item => (byte) (item == '0' ? 1 : 0))   .toarray();  

test:

console.writeline(string.join(environment.newline, barray   .select((value, index) => $"barray[{index}]=0x{value:x2};"))); 

outcome:

barray[0]=0x00; barray[1]=0x00; barray[2]=0x01; barray[3]=0x01; barray[4]=0x00; barray[5]=0x00; barray[6]=0x01; barray[7]=0x01; 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -