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
6
  • 6
    How are you even using a variable named string? Commented Nov 1, 2013 at 15:38
  • 2
    Why do you expect it to be 15? If anything I would expect it to be 70. Also please post a complete complieable example of the problem, right now your code would not even compile. EDIT: thanks Rik, 102 is f, I checked F. Commented Nov 1, 2013 at 15:38
  • 2
    FYI, 102 is the ascii code for lowercase 'f' Commented Nov 1, 2013 at 15:39
  • 1
    Why do you expect 15? The ASCII code for f is 102. Commented Nov 1, 2013 at 15:39
  • By the way, beware of Unicode. C# strings are UTF16, and can take up to two bytes. Commented Nov 1, 2013 at 15:42

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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').
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...

Comments

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).

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.