1

i'v searched already the forum and got multiple answers but none what i can find answer my problem...

i have the string : "48FF0015E8" and i need to convert it to a byte array like byte[]{48,FF,00,15,E8}, just the same as the string, not converted to something else...

using byte bt = Convert.ToByte("E8", 16) do the job but will fail in Convert.ToByte("48", 16) as it store "72" in the array

i need to loop the string in blocks of 2 chars(1 byte) since i need to make some comparisons and then store in byte array.

for(int x = 0;x<numBytes;x+=2)
{
  string strByte = HexStr.Substring(x, 2) //Loop bytes from string "48FF0015E8" 
  byte bt = Convert.ToByte(strByte, 16); // here is where i have problems
  offset += 2;
}
  • Why doesn't this help? https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array – Stefan Jun 06 '20 at 20:31
  • Or better: https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa ? – Stefan Jun 06 '20 at 20:32
  • 1
    _but will fail in Convert.ToByte("48", 16) as it store "72" in the array_ - but that is exactly what you ask for, it should store 72 (=0x48) in the array. – wimh Jun 06 '20 at 20:34
  • I'm not following, what is wrong with `Convert.ToByte("48", 16)`? – Guru Stron Jun 06 '20 at 20:37
  • 1
    It is quite clear that problem you have *is not written in the question* at this point. What question asks currently is indeed duplicate of extremely well answered "hex to string and back" question. You may either [edit] this question to clarify what you expect as input and output (with clear explanation on why) or ask new question with the same clarifications. Please note that complaining that 0x48 should not be 72 is only going to make people confused (at best) on what you are asking - so make sure explanation are clear and reasonable. – Alexei Levenkov Jun 06 '20 at 20:42

1 Answers1

0

You can try this

    long number = Convert.ToInt64("48FF0015E8", 16);
    byte[] bytes = BitConverter.GetBytes(number);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(bytes);
    var result = bytes.ToList().Skip(3).ToList();

https://dotnetfiddle.net/H5cFOk

janmbaco
  • 340
  • 4
  • 11