how can I create a byte data type from a string? For example: The device I am sending data to, expects the data to be in the hexadecimal format. More specifically, it needs to be in the format: 0x{hexa_decimal_value}
Hard coded, it already worked sending data this way. I would create a byte array like this:
byte[] items_to_send_ = new byte[] {0x46, 0x30, 0x00};
Now I want to code it dynamically.
The code I am now trying to write looks like this:
var ListByte = new List<byte>();
foreach (char val in messageToConvert)
{
var hexa_decimal_val = Convert.ToInt32(val).ToString("X");
hexa_decimal_val = $"0x:{hexa_decimal_val}";
byte val_ = CreateByteFromStringFunction(hexa_decimal_val); // How?
ListByte.Add(val_);
}
The step in question is when creating the variable val_
, where I want to build the byte value from hexa_decimal_val
, but I just don't know how. Casting does not work, and I did not find any other function that would do it for me.
It feels like there should be a really easy solution to this, but I just don't seem to find it.
What makes looking for the correct answer tricky here is that I already know how to convert from string to hexadecimal value, but the conversion afterwards is nowhere to be found.
CodePudding user response:
You don't need to do create bytes from characters one by one and append to a list. You can usethis;
var encodedByteList = Encoding.UTF8.GetBytes(messageToConvert);
If you still want to do that, you can do something like this;
var encodedByteList = new List<byte>();
foreach (var character in messageToConvert)
{
var correspondingByte = (byte)character;
encodedByteList.Add(correspondingByte);
}
Or with LINQ, you can use this one liner;
var encodedByteList = messageToConvert.Select(c => (byte)c);