将C语言中的printf(%c)转换为C#

5

我正在尝试将这个C printf转换为C#

printf("%c%c",(x>>8)&0xff,x&0xff);

我尝试过类似以下的代码:

int x = 65535;

char[] chars = new char[2];
chars[0] = (char)(x >> 8 & 0xFF);
chars[1] = (char)(x & 0xFF);

但是我得到了不同的结果。 我需要将结果写入文件, 所以我正在做这个:

tWriter.Write(chars);

也许这就是问题所在。 谢谢。

使用C版本会得到什么结果?使用C#版本会得到什么结果? - zneak
对于这个值 -> 65535 C 返回 -> ÿÿ C# 返回 -> ÿÿ - Rias
我可能错了,但我认为当将ÿ解释为Windows-1252而不是UTF-8时,ÿ是UTF-8序列。 - dreamlax
3个回答

3
在.NET中,char变量以无符号16位(2字节)数字存储,取值范围从0到65535。因此,请使用以下代码:
        int x = (int)0xA0FF;  // use differing high and low bytes for testing

        byte[] bytes = new byte[2];
        bytes[0] = (byte)(x >> 8);  // high byte
        bytes[1] = (byte)(x);       // low byte

1
如果您要使用BinaryWriter,那么只需进行两次写操作即可:
bw.Write((byte)(x>>8));
bw.Write((byte)x);

请记住,您刚刚执行了大端写入。如果要将其作为16位整数读取,并且期望以小端形式读取,请交换写入顺序。

0

好的,

我使用Mitch Wheat的建议,并将TextWriter更改为BinaryWriter来解决问题。

以下是代码:

System.IO.BinaryWriter bw = new System.IO.BinaryWriter(System.IO.File.Open(@"C:\file.ext", System.IO.FileMode.Create));

int x = 65535;

byte[] bytes = new byte[2];
bytes[0] = (byte)(x >> 8);
bytes[1] = (byte)(x);

bw.Write(bytes);

感谢大家。 特别感谢 Mitch Wheat。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接