Skip to content

Numeric Examples

Chris Dahlberg edited this page Mar 19, 2019 · 2 revisions

Bitmask

Bitmask provides constants helpful when manipulating integer-based values, for example to get the upper or lower half of a 64-bit integer value.

long int64Value = int.MaxValue;

// Get the upper 32 bits of a 64-bit integer as a 32-bit integer
int upper32Bits = (int)(int64Value & Bitmask.Int64Upper32 >> 32);

// Get the lower 32 bits of a 64-bit integer as a 32-bit integer
int lower32Bits = (int)(int64Value & Bitmask.Int64Lower32);

PackedInt16 / PackedInt32 / PackedInt64

PackedInt16, PackedInt32, and PackedInt64 allow multiple numeric values to be easily stored in and accessed from a single larger numeric value.

// In addition to constructors, there are implicit conversions from primitive integer types to packed integer types:
PackedInt16 packed16BitInteger = 42;

// A 16-bit integer can store two independent 8-bit integers (i.e. bytes):
byte firstByte = packed16BitInteger.LowerByte;
byte secondByte = packed16BitInteger.UpperByte;

// Packed integers are immutable. To get a new packed integer, values can be passed in to the constructor or the
// With* methods can be called:
var newPackedInt16a = new PackedInt16(firstByte, (byte)(secondByte + 1));
var newPackedInt16b = packed16BitInteger.WithUpperByte((byte)(secondByte + 1));
Clone this wiki locally