>8)&0xff,x&0xff); I tried something like this: ...">

Convert C printf (% c) to C #

I am trying to convert this C printf to C #

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

I 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 have different results. I need to write the result to a file so I do this:

 tWriter.Write(chars); 

Perhaps this is a problem.

Thanks.

+4
source share
3 answers

In .NET, char variables are stored as unsigned 16-bit (2 byte) numbers ranging from 0 to 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 
+3
source

If you are going to use BinaryWriter, not just two entries:

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

Keep in mind that you just recorded Big Endian. If it should be read as a 16-bit integer with what expects it in Little Endian form, replace the entries around.

+1
source

Good,

I got it using the Mitch Wheat offer 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 for Mitch wheat.

0
source

All Articles