Contact

Subscribe via Email

Subscribe via RSS/JSON

Categories

Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan

Elsewhere

Getting the ASCII/ UTF-8 value of a string

To display the character associated with an ASCII/ UTF-8 code do the following:

Thanks to this PowerTip.

Now how about the reverse? Can I get the ASCII/ UTF-8 code of a character.

No luck. But I think am the right track.

The error InvalidCastFromStringToInteger is what tells me PowerShell is trying to cast from a [string] to [int] – which is not what I want and will obviously fail. I want to cast from a [char] to [int] so let’s be explicit about that.

Good, that works!

Now how about getting the ASCII/ UTF-8 of a string. Can I do that?

As expected, you can’t just pass two characters and hope it works!

What I need is an array of [char] elements. Which I can then type cast to an array of [int] elements.

First let’s look whether there’s any method available to convert a string to an array of characters?

Looks like there is. Does the following work?

No, but that gives me a hint on the solution. The output of the ToCharArray() method is of the data type System.Char[] whereas [char] is shorthand for the System.Char data type.

So maybe [char[]] is what I need? Does such a data type exist?

Sure enough it does!

So let’s try the following:

I don’t need the ToCharArray() method either as if I just type cast a string to an array of characters the method is invoked implicitly. Sweet!

Armed with this info I try type casting the string to an array of integers to get their ASCII/ UTF-8 values:

Nice!

Can I make this better? As in, say I had a longish string; currently the above snippet just gives a bunch of codes and that’s not very helpful if I want to see the code of a particular letter. Can I get the output such that it shows each character followed by it’s ASCII/ UTF-8 code? Something like this:

D’oh! Doesn’t help. But I am on the right track, and I know what to do. You see, within double quotes the [int] is not evaluated (thanks to this Hey, Scripting Guy! post) and so I have to force evaluation through any one of the methods mentioned in that post. I prefer the VBScript approach, so here goes:

Bingo!

Getting the ASCII/ UTF-8 value of a string by rakhesh is licensed under a Creative Commons Attribution 4.0 International License.