Igor Henriques
Igor Henriques

Reputation: 307

How to literaly turn a string value into a value of a byte?

I have a list of strings with values like these:

example[0] = "0xFF";
example[1] = "0xA8";

What I'm trying to do is literally set those values as values of bytes, like:

byte x = Convert.ToByte(example[0]);
byte y = Convert.ToByte(example[1]);

Sooo, how can I do it?

Note: I literally need the byte variable contains "0xFF" as its value, for example...

Upvotes: 0

Views: 348

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

just use ToByte with the appropriate Base. ToByte will convert both values FF and literals 0xFF, so there is no need to remove the 0x

var byte = Convert.ToByte(hex, 16)

or

var hexes = new string[] { "0xFF", "0xA8"};
var results = hexes.Select(x => Convert.ToByte(x, 16))
                   .ToArray();

foreach (var item in results)
    Console.WriteLine(item);

Output

255
168

Update

but there's some way to convert those strings keeping the Hex structure? You know: byte x = 0xFF;

var hexes = new string[] { "0xFF", "0xA8" };
var results = hexes.Select(x => $"byte {Convert.ToByte(x, 16)} = {x}")
                   .ToArray();

foreach (var item in results)
   Console.WriteLine(item);

Output

byte 255 = 0xFF
byte 168 = 0xA8

Full Demo Here


Additional Resources

ToByte(String, Int32)

Converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer.

Upvotes: 3

Related Questions