tags:

views:

130

answers:

3

Hi,

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 result to a file so I'm doing this:

tWriter.Write(chars);

Maybe that is the problem.

Thanks.

+3  A: 

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
Mitch Wheat
A: 

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.

Ervilha
+1  A: 

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.

Tergiver
Thanks for the tip.
Ervilha