Moritz
Moritz

Reputation: 153

C# reversed ushort

I'm currently having a problem with some Socket stuff.

The output that I want is 0x5801, which reversed is 0x0158which is actually 344 as ushort.

ushort t = 344;
p.WriteString("\x58\x01", false);

I now want to have the variable instead of the hardcoded hex. I already tried with some ReverseBit classes and so on, but nothing really worked.

Thanks for your help!

Upvotes: 0

Views: 2380

Answers (4)

Douglas
Douglas

Reputation: 54877

The order of the bytes returned by the BitConverter.GetBytes method depends on the endianness of your computer architecture; however, so does the order of the bytes expected by BitConverter.ToString, meaning that you do not have to perform any manual reversing if both operations are performed on the same machine.

ushort t = 344;
byte[] bytes = BitConverter.GetBytes(t);
string hex = BitConverter.ToString(bytes);
hex = hex.Replace("-", "");
p.WriteString(hex);

Upvotes: 1

Tergiver
Tergiver

Reputation: 14507

Sounds like you want IPAddress.HostToNetworkOrder and NetworkOrderToHost

http://msdn.microsoft.com/en-us/library/fw3e4a0f

Upvotes: 2

Tim S.
Tim S.

Reputation: 56536

I think this is what you're trying to do:

ushort t = 344;
var b = BitConverter.GetBytes(t);
if (!BitConverter.IsLittleEndian)
    Array.Reverse(b);
//write b

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

Start off by not using WriteString. You want to write binary data, right? So either use WriteShort or write the bytes directly.

You haven't given much information to work with (like the type of p, or what this data is meant to represent) but if this is a problem of endianness, you could consider using my MiscUtil which has EndianBinaryWriter and EndianBinaryReader which are like the framework BinaryWriter andBinaryReader classes, but with the ability to specify endianness.

Upvotes: 6

Related Questions