UInt64

public extension UInt64

This extension will add a new set of capabilities to the native UInt64 data type.

  • This method allows us to mask a discrete bit range within the number, and return its value as a 64-bit unsigned Int.

    For example, if we have the hex number 0xF30 (3888 decimal, or 111100110000 binary), we can mask parts of it to get masked values, like so:

       // 111100110000 (Value, in binary)
    
       // 111111111111 (Mask, in binary)
       let wholeValue = 3888.maskedValue(firstPlace: 0, runLength: 12)     // Returns 3888
       // 111111110000
       let lastByte = 3888.maskedValue(firstPlace: 4, runLength: 8)        // Returns 243
       // 000000000011
       let lowestTwoBits = 3888.maskedValue(firstPlace: 0, runLength: 2)   // Returns 0
       // 000000111100
       let middleTwelve = 3888.maskedValue(firstPlace: 2, runLength: 4)    // Returns 12
       // 000111100000
       let middleNine = 3888.maskedValue(firstPlace: 5, runLength: 4)      // Returns 9
       // 011111111111
       let theFirstElevenBits = 3888.maskedValue(firstPlace: 0, runLength: 11) // Returns 1840
       // 111111111110
       let theLastElevenBits = 3888.maskedValue(firstPlace: 1, runLength: 11)  // Returns 1944
       // 000000110000
       let lowestTwoBitsOfTheSecondHalfOfTheFirstByte = 3888.maskedValue(firstPlace: 4, runLength: 2)          // Returns 3
       // 000001100000
       let secondToLowestTwoBitsOfTheSecondHalfOfTheFirstByte = 3888.maskedValue(firstPlace: 5, runLength: 2)  // Returns 1
       // 000011000000
       let thirdFromLowestTwoBitsOfTheSecondHalfOfTheFirstByte = 3888.maskedValue(firstPlace: 6, runLength: 2) // Returns 0
    

    This is useful for interpeting bitfields, such as the OBD DTS response.

    This is BIT-based, not BYTE-based, and assumes the number is in a linear (bigendian) format, in which the least significant bit is the rightmost one (position one). In reality, this doesn’t matter, as the language takes care of transposing byte order.

    Bit 1 is the least signficant (rightmost) bit in the value. The maximum value for firstPlace is 64. Run Length means the selected (by firstPlace) first bit, and leftward (towards more significant bits). It includes the first bit.

    The UInt64 variant of this is the “main” one.

    • prerequisites:

      • The sum of firstPlace and runLength cannot exceed the maximum size of a UInt64.

    Declaration

    Swift

    func maskedValue(firstPlace inFirstPlace: UInt, runLength inRunLength: UInt) -> UInt64

    Parameters

    firstPlace

    The 1-based (1 is the first bit) starting position for the mask.

    runLength

    The inclusive (includes the starting place) number of bits to mask. If 0, then the return will always be 0.

    Return Value

    An Unsigned Int, with the masked value.