0

I've got this code

BitConverter.GetBytes(width).CopyTo(resultBytes, 0);

If the width is 12 it returns one byte not 4, is there a built in function to resize the array leaving 0's at the beginning to output [0, 0, 0, 12] instead of [12].

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36

3 Answers3

2

What is the type of width? Bit converter just converts the type to an array of appropriate size. If you say

long  x = 1 ;
int   y = 2 ;
short z = 3 ;

byte[] x_bytes = BitConverter.GetBytes(x) ;
byte[] y_bytes = BitConverter.GetBytes(y) ;
byte[] z_bytes = BitConverter.GetBytes(z) ;

You'll get back 8-, 4- and 2-byte arrays, respectively. You can cast to the desired type:

byte[] bytes = BitConverter.GetBytes( (int) x ) ;

And if you say something like

byte[] bytes = BitConverter.GetBytes(1) ;

You'll get back an array of 4 bytes: the type of an unsuffixed integer literal is the smallest type in which will fit, in order of preference: int, uint, long, ulong. If the literal is suffixed, it will be the type specified by the suffix (e.g., 1L will give you an 8-byte long).

If you are converting an expression, such as:

byte[] bytes = BitConverter.GetBytes( ((3*x + 2&y + z) << 3 ) & 5L ) ;

What gets converted is, of course, the type produced by evaluating the expression.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
1

you need to cast width to int in order to get 4 bytes, because the result of GetBytes() is dependent on the type passed in:

    BitConverter.GetBytes((int)width).CopyTo(resultBytes, 0);
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
0

Maybe it's the simplest solution ever, but what about Array.Reverse:

BitConverter.GetBytes(4).CopyTo(resultBytes, 0); // [4, 0, 0, 0]
Array.Reverse(resultBytes); // [0, 0, 0, 4]
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206