Dan
Dan

Reputation: 1262

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

Upvotes: 1

Views: 1547

Answers (5)

KeithS
KeithS

Reputation: 71591

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
            }

Upvotes: 0

escargot agile
escargot agile

Reputation: 22399

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

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

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

Upvotes: 0

vidstige
vidstige

Reputation: 13085

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

Upvotes: 2

LukeH
LukeH

Reputation: 269658

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.

Upvotes: 2

Related Questions