From ushot to byte[]

  • Thread starter Salvatore Di Fazio
  • Start date
S

Salvatore Di Fazio

Hi guys,
I've a ushort variable and I need to copy it in an array of byte.
I wrote:

m_bMsg[0] = (byte) (p_sTrackNumber & 0xff00 >> 8);
m_bMsg[1] = (byte) (p_sTrackNumber & 0x00ff >> 16);

but I would like to know if exist a better way by a C# class.
Tnx
 
S

Siva M

Hi,

Check out BitConverter.GetBytes(). This just gets the bytes as an array.

Hi guys,
I've a ushort variable and I need to copy it in an array of byte.
I wrote:

m_bMsg[0] = (byte) (p_sTrackNumber & 0xff00 >> 8);
m_bMsg[1] = (byte) (p_sTrackNumber & 0x00ff >> 16);

but I would like to know if exist a better way by a C# class.
Tnx
 
A

Andrew Kirillov

Hello

I am not sure about the better way, but your sample is not the best one,
because it's totaly wrong.
More corectly will be:

m_bMsg[0] = (byte)(sTrackNumber & 0xFF); // low byte
m_bMsg[1] = (byte)((sTrackNumber >> 8) & 0xFF); // hi byte

Of course we can swap bytes order. But you need not to shift anything by 16
bits.
 
H

Hasan O

Hi,
byte[] a = System.encoding.ascii.getstring("strTobeConverted");
search for System.encoding.ascii.* for ushort variables. This gonna helps
you.
 
J

Jon Skeet [C# MVP]

Hasan O said:
byte[] a = System.encoding.ascii.getstring("strTobeConverted");
search for System.encoding.ascii.* for ushort variables. This gonna helps
you.

No, Encodings are for *text* - there's no text involved here as far as
I can tell, just a ushort and bytes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top