Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1449

Code for working with Unsigned Shorts

$
0
0
In VB6, the Integer data type is equivalent to a Short (signed short) in C. Now when you encounter a UShort (unsigned short) in a file or in a structure returned from a DLL call, what do you do? You can either hope that the value stored in it happens to be less than 32768 (a region in which Shorts and UShorts are identical), or try to find a way to get the full range of possible UShort values represented in VB6. My code here does the latter.

Code:

Private Function UShortToInt(ByVal Value As Integer) As Long
    UShortToInt = Value And &HFFFF&
End Function

Private Function IntToUShort(ByVal Value As Long) As Integer
    IntToUShort = (Value And &H7FFF) - (Value And &H8000)
End Function


When you get a UShort value, you simply use UShortToInt to convert it to Int (what's called Long in VB6), which even though it is technically a signed data type it can represent all positive values that UShort can. This gives you access to the full range of values that you were intended to be able to have access to in the UShort field from whatever file you read the data from. If you need to save a UShort to file, just work with the data in an Int and then use IntToUShort to convert it to a UShort prior to saving it to the file.

Viewing all articles
Browse latest Browse all 1449

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>