Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

BitConverter return wrong bytes?

I am trying to convert values to byte arrays.

For example, I have:

var b1 = BitConverter.GetBytes(0x85);
var b2 = BitConverter.GetBytes(12345);

The value of b1 is:

{byte[4]}
    [0]: 133
    [1]: 0
    [2]: 0
    [3]: 0

And of b2:

{byte[4]}
    [0]: 57
    [1]: 48
    [2]: 0
    [3]: 0

Why does the byte array always have a size of 4? And is it possible to return the correct number of bytes (ie. excluding trailing 0's)?

Upvotes: -1

Views: 2028

Answers (2)

Joey
Joey

Reputation: 354546

Four bytes is the correct number of bytes for a 32-bit integer. If you want it truncated to the minimum number of bytes necessary to represent a number, you'd have to do so yourself. There are actually very few applications for what you're looking for. BitConverter is for getting at the exact memory representation of certain primitive types. Something that is helpful for binary file formats or network protocols. For those things you usually want to get the same length for a result, which is based on the type you passed in.

Side note: Would you want 0 to result in an empty array? What about -1? Should that be new byte [] { 255 } or new byte [] { 255, 255, 255, 255 }?

Upvotes: 7

Nico
Nico

Reputation: 3542

you are passing an int which has 32bits. You could pass a short and you would get 2 bytes instead:

var b1 = BitConverter.GetBytes((short)0x85);
var b2 = BitConverter.GetBytes((short)12345);

Upvotes: 1

Related Questions