2010-08-13 36 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