Raleigh Krezzler
Raleigh Krezzler

Reputation: 9

Alternative to BitConverter that doesn't require fixed length, zero-padded byte arrays?

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:

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

Answers (1)

Sedat Kapanoglu
Sedat Kapanoglu

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

Related Questions