简体   繁体   中英

C# reversed ushort

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

The output that I want is 0x5801 , which reversed is 0x0158 which 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!

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 and BinaryReader classes, but with the ability to specify endianness.

Sounds like you want IPAddress.HostToNetworkOrder and NetworkOrderToHost

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM