0

I have a Byte from my database, stored as 0-254

i can convert it from a Byte to string using

byteVal.ToString() //0 return 0 20 returns 20

but to then return it back to a Byte I cannot figure out.

f1wade
  • 2,557
  • 6
  • 22
  • 39
  • 2
    http://msdn.microsoft.com/en-us/library/k0s9b1y3(v=vs.110).aspx – Tim Schmelter Dec 05 '14 at 14:21
  • possible duplicate of [Converting a string to byte-array without using an encoding (byte-by-byte)](http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte) – Dylan Corriveau Dec 05 '14 at 14:22
  • @DylanCorriveau no this question has nothing to do with that. – Selman Genç Dec 05 '14 at 14:23
  • possible duplicate of [How to Convert string to byte in C#](http://stackoverflow.com/questions/10556805/how-to-convert-string-to-byte-in-c-sharp) – faby Dec 05 '14 at 14:27

2 Answers2

1

Similar to other number-types you need the appropriate Parse-method, in this case Byte.Parse:

Byte b = Byte.Parse("20");

If you don't know if the format is valid you can use Byte.TryParse:

Byte b;
if(!Byte.TryParse("256", out b))
    Console.WriteLine("Not a valid byte");
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • great thanks, that works, for some reason i thought it might give an ascii byte value back. but i use Byte.TryParse(string); just in case it is not compatible. – f1wade Dec 05 '14 at 14:27
0

You can use the Convert.ToByte overload which converts string to a byte

vc 74
  • 34,724
  • 7
  • 58
  • 80