0

I have a string which i would need to convert back to its original byte array.

byte[] frame = new frame[64]; 
//Frame has values : 0x01,0x04,0x00,0x00,0x00,0x0A,0x70,0x0D

//TotalLengthofRecivedPackage = 8  
string Payload ; 

StringBuilder builder = new StringBuilder();
for ( int i = 0; i < TotalLengthofRecivedPackage; i++ )
{
    builder.Append(frame[i].ToString("x2"));
}
this.Payload = builder.ToString();

after this I was able to get this.Payload set as 01040000000A700D NOw i would like to recreate back this byte array with contents as 0x01,0x04,0x00,0x00,0x00,0x0A,0x70,0x0D is this possible,

I have tried to use byte[] recreatedbytesarray = payload.Select(c => ( byte ) ( c - '0' )).ToArray(); but with this the bytes i get is 0x00,0x01,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0A,0x70,0x0D which is literraly each character changed to a number but i need 2 digits to be considered as a number.

Any help would be appreciated.Thank you.

phuzi
  • 12,078
  • 3
  • 26
  • 50
  • 1
    Could you show us what you have tried so far? – phuzi Apr 01 '21 at 12:54
  • `byte[] frame = new frame[64];` This won't compile. –  Apr 01 '21 at 13:13
  • @phuzi i have tried byte[] recreatedbytesarray = payload.Select(c => ( byte ) ( c - '0' )).ToArray(); and the result is pasted above. – Prashanjit Ghosh Apr 01 '21 at 13:28
  • @NineBerry thank you so much for you to point me to the correct place. I used the above told suggestion and it works flawless. I get my desired payload as {0x01,0x04,0x00,0x00,0x00,0x0A,0x70,0x0D} byte[] payloadbytes = Enumerable.Range(0, payload.Length / 2).Select(x => Byte.Parse(payload.Substring(2 * x, 2), NumberStyles.HexNumber)).ToArray(); – Prashanjit Ghosh Apr 01 '21 at 13:38

0 Answers0