2

I am trying to convert a string into a byte array. When I look at individual elements of the The byte array I get unexpected results. For example, when I look at the first element, which was "F", I expect it to be converted to 15, but instead I get 102. Is there an error here?

 Console.WriteLine("string[0] = " + string[0]);
 Byte[] data = Encoding.ASCII.GetBytes(string);
 Console.WriteLine("data[0] = " + data[0]);

 string[0] = f
 data[0] = 102
Ann
  • 663
  • 3
  • 12
  • 17

4 Answers4

4

That ASCII.GetBytes returns the ASCII codes of the characters. It would happily accept a string "z{}".

I guess you want to convert a hexadecimal string to the integer value. You need Int32.Parse for that, with the NumberStyles parameter set to NumberStyles.HexNumber.

string s = "1F";
int val = Int32.Parse(s, System.Globalization.NumberStyles.HexNumber);

val would now be 31.

Hans Kesting
  • 34,565
  • 7
  • 74
  • 97
  • Thanks, this is exactly what I needed. Is there a way to use it for chars as well? I am trying with no luck so far. – Ann Nov 01 '13 at 16:10
  • You could use the `.ToString()` method to convert the char into a string. Then you can parse it. Or just use a `switch` for those 16 values (guessing that it's a '0' through 'F'). – Hans Kesting Nov 04 '13 at 08:33
2

Lower case f is 102. Upper case F is 70. Please check http://www.asciitable.com

When you say you were expecting 15, my guess is you saw F in the hex column...

David Arno
  • 40,354
  • 15
  • 79
  • 124
2

Are you expecting 15 because you've looked at something like asciitable.com and seen that the Hex decimal value for the HEX value 'F' is 15?

The decimal value for 'f' is 102 (it's part way down the fourth column in the linked page).

Rob
  • 43,549
  • 23
  • 115
  • 144
0

your expectation is wrong , your code is working fine, Decimal value for lower case 'f' is 102.

Sudhakar Tillapudi
  • 24,787
  • 5
  • 32
  • 62