开发者

Convert a C printf(%c) to C#

I'm trying to convert this C printf to C#

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

I've tried something like this:

int x = 65535;

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

But I'm getting different results. I need to write the r开发者_如何学运维esult to a file so I'm doing this:

tWriter.Write(chars);

Maybe that is the problem.

Thanks.


In .NET, char variables are stored as unsigned 16-bit (2-byte) numbers ranging in value from 0 through 65535. So use this:

        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


If you're going to use a BinaryWriter than just do two writes:

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

Keep in mind that you just performed a Big Endian write. If this is to be read as an 16-bit integer by something that expects it in Little Endian form, swap the writes around.


Ok,

I got it using the Mitch Wheat suggestion and changing the TextWriter to BinaryWriter.

Here is the code

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

Thanks to everyone. Especially to Mitch Wheat.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜