From ushot to byte[]

  • Thread starter Thread starter Salvatore Di Fazio
  • Start date 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
 
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
 
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.
 
Hi,
byte[] a = System.encoding.ascii.getstring("strTobeConverted");
search for System.encoding.ascii.* for ushort variables. This gonna helps
you.
 
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.
 
Back
Top