1

I know I can use bitconverter.GetBytes to get the bytes from an integer. However, I need an array where the contents can be compared for sort order.

e.g.

var plusOne = BitConverter.GetBytes(1);
yields bytes: 0,0,0,1

var plusOne = BitConverter.GetBytes(2);
yields bytes: 0,0,0,2

So far so good:

but:

var minusOne = BitConverter.GetBytes(-1);
yields bytes: 255,255,255,255

Nothing strange here. But comparing the minusOne byte array with the plusOne bytearray would say that the minusOne byte array is greater than the plusOne (255 > 0)

Is there any fancy way to shift, xor etc, so that Int.Min would give 0,0,0,0 and int.Max would give 255,255,255,255 ??

Sorry for the confusion :)

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193

1 Answers1

2

Simply add int.MaxValue + 1 to the current value casted to an uint to preserve the range like:

var result = BitConverter.GetBytes((uint)((long)input - int.MinValue));
dtb
  • 213,145
  • 36
  • 401
  • 431
Polity
  • 14,734
  • 2
  • 40
  • 40
  • I came up with this solution ´unchecked((uint)(int.MinValue ^ (1 << 31))) doesnt need to fall over into a bigger datatype there.. – Roger Johansson Oct 28 '11 at 10:37