简体   繁体   中英

Convert string element to byte

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

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.

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

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

你的期望是错误的,你的代码工作正常,小写'f'的十进制值是102。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM