Char: Compare

Compare

Compares two character code units.



 Public Function Compare(
	  ByVal a As Long,
	  ByVal b As Long ) As Long

Parameters

a
[ByVal] Long. A character to compare with.
b
[ByVal] Long. A character to compare with.

Return Values

Long -  A signed number indicating the position of a parameter in the sort order in relation to the b parameter.
Return Value Description
Less than zeroa precedes b.
Zeroa has the same position in the sort order as b
Greater than zeroa follows b in the sort order.

Remarks

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&.

Exceptions

ExceptionCondition
ArgumentOutOfRangeException a is outside of the valid range -32768 to 65535.
-or-
b is outside of the valid range -32768 to 65535.

Examples

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)

See Also

Project CorLib Overview

Class Char Overview

ConvertToInt32

ConvertFromInt32