Reputation: 341
I have in input the string: "0080801D803480002A1168301FE16E09" and when i convert it to byteArray with the code:
Convert.ToByte(inputWrite.Substring(i, 2), 16);
I get the byte array in first position = "0", but i need to have "00", so when i convert it again into a String a don't get "08" but "00" at the begining.
i get in the and the string "080801D80348002A1168301FE16E9"
and like this i'm missing some important 0, that i need to convert then from this last string to byte again and to decimal values.
Upvotes: 1
Views: 4676
Reputation: 6349
You seem to be confusing things. Because each byte is represented by two characters, bytes array will be two times shorter than the string. When parsing back, you have to make sure that each byte must be converted to two-characters string, even if it is less than 0x10, i.e. does not require second character.
That said, you can use following LINQ oneliner:
string convertedBack = string.Join(string.Empty, bytes.Select(x => x.ToString("X2")).ToArray());
Upvotes: 0
Reputation: 172618
You can also do this using LINQ:
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
You can also refer this
Upvotes: 0
Reputation: 50184
Once you have your byes in an array, there's no difference between 0
and 00
.
What you need to do is, when converting those bytes back to a string, make sure you put any leading zeros back in. You can do this by calling
string byteAsTwoDigitString = myByte.ToString("X2");
The X
says "as hexadecimal", the 2
says "with at least two digits".
Upvotes: 3