I need to check for a string
located inside a packet that I receive as byte
array. If I use BitConverter.ToString()
, I get the bytes as string
with dashes (f.e.: 00-50-25-40-A5-FF).
I tried most functions I found after a quick googling, but most of them have input parameter type string
and if I call them with the string
with dashes, It throws an exception.
I need a function that turns hex(as string
or as byte
) into the string
that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is string
, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because BitConverter
doesn't convert correctly.
To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.
Hexadecimal Number String. The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system and are a popular choice for representing long binary values because their format is quite compact and much easier to understand compared to the long binary strings of 1's and 0's.
Like so?
static void Main() { byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72"); string s = Encoding.ASCII.GetString(data); // GatewayServer } public static byte[] FromHex(string hex) { hex = hex.Replace("-", ""); byte[] raw = new byte[hex.Length / 2]; for (int i = 0; i < raw.Length; i++) { raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); } return raw; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With