Char: Compare |
Compares two character code units.
Public Function Compare( ByVal a As Long, ByVal b As Long ) As Long
Return Value | Description |
---|---|
Less than zero | a precedes b. |
Zero | a has the same position in the sort order as b |
Greater than zero | a follows b in the sort order. |
The range of Unicode code points that represent a character in Visual Basic is U+0000 to U+FFFF (0 to 65535). VBCorLib internally represents characters using the Integer type which has a range from -32768 to 32767. This usually does not present an issue, however, when the need to compare two characters occurs the characters must be converted to correctly handle the 16 bit representation. For instance an Integer value of -1 is Unicode code point U+FFFF which should be the largest code point value during a comparison. In order to correctly compare two characters they are converted to a Long type then ANDed with 0x0000FFFF in order to get a correct ordered representation. The result has an identical 16 bit representation that can be compared correctly.
This method handles character code range -32768 to 65535. A bitwise AND is performed to convert the negative values to their corrisponding positive values. For example -1 is converted to 65535 (U+FFFF) using the bitwise AND operation with a Long type using value = value And &H0000FFFF&
.
Exception | Condition |
---|---|
ArgumentOutOfRangeException |
a is outside of the valid range -32768 to 65535. -or- b is outside of the valid range -32768 to 65535. |
The following example compares several Integer to Long character values demonstrating 16 bit comparisons.
Public Sub Main() ShowComparison 32767, -1 ShowComparison -1, 65535 ShowComparison -32768, 1 End Sub Private Sub ShowComparison(ByVal a As Integer, ByVal b As Long) Dim Relation As String Select Case Char.Compare(a, b) Case Is < 0 Relation = "<" Case Is > 0 Relation = ">" Case Else Relation = "=" End Select Debug.Print CorString.Format("{0,7}({0:X4}) {1} {2,7}({2:X8})", a, Relation, b) End Sub ' This code produces the following output. ' ' 32767(7FFF) < -1(FFFFFFFF) ' -1(FFFF) = 65535(0000FFFF) ' -32768(8000) > 1(00000001)