2010-08-13 56 views
4

我想这个C的printf为C#转换一个C的printf(%C)到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); 

也许这就是问题所在。

谢谢。

+0

使用C版本得到了什么结果,以及使用C#版本得到的结果是什么? – zneak 2010-08-13 00:19:35

+0

对于此值 - > 65535 C返回 - >ÿÿ C#返回 - >ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ – Rias 2010-08-13 00:24:38

+0

我可能是错的,但我认为Ã是UTF-8序列的ÿ解释为Windows-1252而不是UTF-8。 – dreamlax 2010-08-13 00:38:19

回答

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 
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); 

感谢大家。 特别是米奇小麦。

1

如果你要使用的BinaryWriter不仅仅是做两条写道:

bw.Write((byte)(x>>8)); 
bw.Write((byte)x); 

请记住,你只是执行大端写。如果这是要以Little Endian形式预期的16位整数读取,请将写入交换。

+0

感谢您的提示。 – Rias 2010-08-14 01:02:58