Bit of a weird one here but I'm trying to write a control program for a monitor that uses a serial RS232 port to receive commands in hexadecimal, 0xFF, notation i.e. 0x00.
Problem I have is that I can't seem to find a way of taking a user input, which is a decimal value like 55, and converting it into its byte, hexadecimal, form with the above mentioned format. Using the Convert method that Visual studio has built in gives me the correct value i need but without the required 0x at the beginning.
I'm new to using bytes and byte arrays in C# so forgive me if I've missed out on a simple formatting method that will solve it.
Below is a string to byte array method that I found on here and its helpful but gives me the wrong format for the bytes.
private static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i+2, 2), 16);
return bytes;
}
if (hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { hex = hex.Substring(2); }
at the beginning, which will remove the prefix (if extisting) so that the existing code can process the hexstring. – ckuri0x
to a byte, only to a string where your binary data might be represented as hex data e.g.$"0x{bytes[0]}0x{bytes[1]}0x{bytes[2]}"
. Does the monitor require0xA6
as hex formatted string or as byte? You may assume 0x to be in front of the byte, but that is only for human readabiltiy of binary data. If you right click in the watch window of your debugger session you could enable Hexadecimal Display then you will see 0x in front of your byte variables as well... – MarkusEgle