Reputation: 9
BitConverter.GetBytes
always returns fixed length arrays for numbers, padded with zeros so that they are precisely 1, 2, 4, or 8 bytes long. Similarly, the decoding methods only accept arrays of certain lengths, depending on the size of the number.
I’d prefer that GetBytes
returned unpadded arrays and that the decoding methods accepted unpadded arrays, so that I’m not always having to do the padding and trimming myself. For example:
GetBytes(100000)
to return { 0x01, 0x86, 0xa0 }
instead of { 0x00, 0x01, 0x86, 0xa0 }
{ 0x01, 0x86, 0xa0 }
to ToInt32
instead of { 0x00, 0x01, 0x86, 0xa0 }
Am I missing some static property or different method of BitConverter—or perhaps some other class or third-party library—that gives me what I want without having to do the padding and trimming myself?
Upvotes: -1
Views: 275
Reputation: 47690
You can write your own implementation of GetBytes()
and ToInt32()
for that.
public byte[] GetBytesVariableLengthArray(uint number)
{
return switch number
{
< 256 => new byte[] { i & 0xFF },
< 65536 => new byte[] { i & 0xFF, (i >> 8) & 0xFF },
< 65536 * 256 => new byte[] { /* ... and it goes on ... */ }
< 65536 * 65536 => new byte[] { /* ... and on ... */ }
};
}
similarly ToInt32()
:
public uint ToInt32FromVariableLengthArray(byte[] bytes)
{
uint result = 0;
switch (bytes.Length)
{
case 4:
result = bytes[3] << 24;
goto case 3;
case 3:
result |= bytes[2] << 16;
goto case 2;
case 2:
result |= bytes[1] << 8;
goto case 1;
case 1:
result |= bytes[0];
break;
}
return result;
}
Upvotes: 0