2

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dankyy1
  • 1,094
  • 2
  • 16
  • 32

2 Answers2

2

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.

msteiger
  • 2,024
  • 16
  • 22
  • also some values have to convert to ULONG,some values have to convert USHORT and somes should convert to SHORT data type how to convert these types ??thnx – dankyy1 Sep 02 '10 at 10:53
  • 1
    i'm googling and found as converting was... string.Format("{0:X16}", 41104) for ushort string.Format("{0:X32}", 41104) for ulong string.Format("{0:X8}", 41104) for byte can be used – dankyy1 Sep 02 '10 at 11:03
  • 1
    Also, `Convert.ToString(, 16)`. – Andrew Morton Jul 27 '13 at 19:58
  • @dankyy1 I think you're looking for X4, X16, X2, respectively. The length specifier is the number of hex digits. – Cory Nelson Jul 27 '13 at 21:32
1

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();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arseny
  • 7,251
  • 4
  • 37
  • 52
  • thnx for your reply .in the code sample above () is forgetten after tmp is defined so code block should be as on 3rd line List tmp = new List(); – dankyy1 Sep 02 '10 at 10:43