Reputation: 2109
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].
Upvotes: 0
Views: 206
Reputation: 20764
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);
Upvotes: 1
Reputation: 74355
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.
Upvotes: 2
Reputation: 64943
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]
Upvotes: 0