简体   繁体   中英

Encoding issue: vbscript “Chr()” to .Net C#

I can't seem to find the answer to this question.

It seems like I should be able to go from a number to a character in C# by simply doing something along the lines of (char)MyInt to duplicate the behaviour of vb's Chr() function; however, this is not the case:

In VB Script w/ an asp page, if my code says this:

Response.Write(Chr(139))

It outputs this:

‹ (character code 8249)

Opposed to this:

(character code 139)

I'm missing something somewhere with the encoding, but I can't find it. What encoding is Chr() using?

Chr() uses the system default encoding, I believe - so it's roughly equivalent to:

byte[] bytes = new byte[] { 139 };
char c = Encoding.Default.GetString(bytes)[0];

On my box (Windows CP1252 as the default) that does indeed give Unicode 8249.

If you want to call something that has exactly the behaviour of VB's Chr from C#, then, why not simply call it rather than trying to deduce its behaviour?

Just put a "using Microsoft.VisualBasic;" at the top of your C# program, add the VB runtime DLL to your references, and go to town.

If you cast an int to a char , you will get the character with the Unicode character code that was in the integer. The char data type is just a 16 bit UTF-16 character code.

To get the equivalent of the VBScript chr() function in .NET you would need something like:

string s = Encoding.Default.GetString(new byte[]{ 139 });

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