문제

I'm trying to convert an int value to a 16-bit unsigned char type (USHORT). In an example, 41104 is A909 in ushort, but in C# I tried with code sample as (with help from MSDN article BitConverter.GetBytes Yöntem (UInt16)):

byte[] bytes = BitConverter.GetBytes(41104);
string bytes = BitConverter.ToString(byteArray);
//It returns "90-A0"

How do I get the A909 value as ushort for 41104?

도움이 되었습니까?

해결책

Actually the correct (=hexadecimal) value is A090. I doesn't matter whether it's ushort or not, what you want is to display the hexadecimal equivalent.

The code snippet you provided already does this. One byte is "A0" the other one "90". You just have to get the order right.

Another way is to let .NET do the job

String.Format("{0:X}", 41104);

As you can see it's not really a data conversion, but rather a different way of display.

다른 팁

You need to reorder the bytes:

byte[] bytes = BitConverter.GetBytes(41104);
if (BitConverter.IsLittleEndian)
{    List<byte> tmp = new List<byte>();
     tmp.AddRange(bytes);
     tmp.Reverse();
     bytes = tmp.ToArray();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top