简体   繁体   English

C#反向Ushort

[英]C# reversed ushort

I'm currently having a problem with some Socket stuff. 我目前在某些Socket方面存在问题。

The output that I want is 0x5801 , which reversed is 0x0158 which is actually 344 as ushort. 我想要的输出是0x5801 ,相反是0x0158 ,实际上是344作为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. 我已经尝试了一些ReverseBit类,等等,但是没有任何效果。

Thanks for your help! 谢谢你的帮助!

Start off by not using WriteString . 从不使用WriteString You want to write binary data, right? 您要写入二进制数据,对吗? So either use WriteShort or write the bytes directly. 因此,可以使用WriteShort或直接写入字节。

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. 您没有提供太多信息来处理(例如p的类型,或此数据表示的意思),但是如果这是字节序问题,则可以考虑使用具有EndianBinaryWriterEndianBinaryReader MiscUtil ,它们类似于框架BinaryWriterBinaryReader类,但是具有指定字节序的能力。

Sounds like you want IPAddress.HostToNetworkOrder and NetworkOrderToHost 听起来像您想要IPAddress.HostToNetworkOrderNetworkOrderToHost

http://msdn.microsoft.com/en-us/library/fw3e4a0f http://msdn.microsoft.com/en-us/library/fw3e4a​​0f

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; BitConverter.GetBytes方法返回的字节顺序取决于您的计算机体系结构的字节顺序。 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. 但是, BitConverter.ToString 期望的字节顺序也是如此,这意味着如果两个操作都是在同一台计算机上执行的,则不必执行任何手动反向操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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