开发者

Converting char to integer representation c#

When I try to run the following code it always spits out the hex representation, not the integer representation. Most of the examples I found on MSDN said this should work. What am I missing?

                var stringBuilder = new StringBuilder("8");
                int j = 0;
                foreach (char item in stringBuilder.ToString())
                {
                    j = Convert.ToInt32(item); //returns 38, need return to be 56
                }

edit I should have made clear that I know the difference it's returning the hex value. I'm outputting the value to a file, and in that file, it still shows the hex value, not the integer, so I don't think it has anything to do with the debugging environment.

edit2 Looks like a PEBKAC problem. Looked at the code that was writing to the file, and it was using a .toString("X") method, changing it to a Hex value. The fact that it was hex in my debug environment was what 开发者_如何学Pythonconfused me.


An int is neither hex nor decimal. It's just a number. Is your debugger set to display hex-values for ints?


How are you viewing/displaying the value?

The '8' character will definitely be converted to 56. I suspect that you're viewing the number in hex format since 56 (decimal) is 38 (hex). You just need to view the number in decimal format instead.


j is an int. An int is always in binary. it's another question how you later display it :)


Are you using hexadecimal display? :) Right-click any of the Watch panels and uncheck "hexadecimal display".


I would try a simple cast to a short or a byte; that has always gotten me the right answer:

var stringBuilder = new StringBuilder("8");
            int j = 0;
            foreach (char item in stringBuilder.ToString())
            {
                j = (byte)item; //should return 56 as expected
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜