Groups | Blog | Home
all groups > dotnet general > october 2004 >

dotnet general : writing ints to file in reverse byte order


PHil Coveney
10/6/2004 11:43:01 PM
Hello,

I need to support a file format that stores integers with the MSB first
and the LSB last. When I use
BinaryWriter aWriter = new BinaryWriter(aFileStream, Encoding.ASCII);
int someValue = 1;
aWriter.WriteInt32(someValue);
the byte stream that appears in the file is
01 00 00 00

What I need for this file format is
00 00 00 01

There does not appear to be anything in Marshal that supports this. Does
anyone have a recommendation?

Thanks in advance,

--
Tom Shelton
10/7/2004 12:04:02 AM
[quoted text, click to view]

You could try using System.Net.IPAddress.HostToNetworkOrder to convert
the integer first....

using System;
using System.Net;

public class test
{
public static void Main ()
{
int i = 1;
int j = IPAddress.HostToNetworkOrder (i);

Console.WriteLine (BitConverter.ToString (BitConverter.GetBytes (i)));
Console.WriteLine (BitConverter.ToString (BitConverter.GetBytes (j)));
}
}

--
Jon Skeet [C# MVP]
10/7/2004 9:29:44 AM
[quoted text, click to view]

You could use my EndianBinaryWriter which allows you to specify
endianness:

http://www.pobox.com/~skeet/csharp/miscutil

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
Dennis Myrén
10/7/2004 9:58:00 AM
You can also do by yourself with some bit shifting:

public void WriteInt32BigEndian ( int value )
{
base.Write( new byte [0x4] {
(byte) (value >> 0x18),
(byte) (value >> 0x10),
(byte) (value >> 0x8),
(byte) (value)
} );
}

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
[quoted text, click to view]

Chris Dunaway
10/7/2004 10:36:38 AM
[quoted text, click to view]

In addition, check out the system.Text.Encoding.BigEndianUnicode encoding
method.

--
Chris

dunawayc[AT]sbcglobal_lunchmeat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
PHil Coveney
10/7/2004 4:23:12 PM
Hi Jon,

Wow, I got several very helpful responses to this post...but yours, the
one that said "use this, it's already done," wins the prize. Thanks for your
help, and your DLL.

PC

[quoted text, click to view]
Jon Skeet [C# MVP]
10/8/2004 7:44:20 AM
[quoted text, click to view]

My pleasure - just let me know if you have any problems with it :)

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button