Reputation: 703
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
Upvotes: 2
Views: 224
Reputation: 26219
your expectation is wrong , your code is working fine, Decimal value for lower case 'f' is 102.
Upvotes: 0
Reputation: 45809
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).
Upvotes: 2
Reputation: 43264
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...
Upvotes: 2
Reputation: 39358
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.
Upvotes: 4