Converting between signed and unsigned numbers.
Posted: Sat Aug 03, 2013 8:04 am
Converting between signed and unsigned numbers.
Taken from a Microsoft Knowledge-base article aimed at VBA.
I have come from a dialect of Basic which uses floating point numbers only so all this discussion about signed/unsigned is interesting.
As I am a very new beginner with PureBasic, any improvements to the code style would be welcome.
Jim
Taken from a Microsoft Knowledge-base article aimed at VBA.
I have come from a dialect of Basic which uses floating point numbers only so all this discussion about signed/unsigned is interesting.
Code: Select all
;unsigned.pbi
;How To Convert Between Signed and Unsigned Numbers
;http://support.microsoft.com/kb/189323
Procedure ErrorHandler()
MessageRequester("OnError", "Overflow error, Code: "+ Str(ErrorCode()))
EndProcedure
Procedure.l UnsignedToLong(Value.q)
Protected OFFSET_4.q = 4294967296, MAXINT_4 = 2147483647
If Value < 0 Or Value >= OFFSET_4
RaiseError(6) ; Overflow
EndIf
If Value <= MAXINT_4
UnsignedToLong.l = Value
Else
UnsignedToLong = Value - OFFSET_4
EndIf
ProcedureReturn UnsignedToLong
EndProcedure
Procedure.q LongToUnsigned(Value.l)
Protected OFFSET_4.q = 4294967296, MAXINT_4 = 2147483647
If Value < 0
LongToUnsigned.q = Value + OFFSET_4
Else
LongToUnsigned = Value
EndIf
ProcedureReturn LongToUnsigned
EndProcedure
Procedure.l UnsignedToWord(Value.l)
Protected OFFSET_2 = 65536, MAXINT_2 = 32767
If Value < 0 Or Value >= OFFSET_2
RaiseError(6); Overflow
EndIf
If Value <= MAXINT_2
UnsignedToWord = Value
Else
UnsignedToWord = Value - OFFSET_2
EndIf
ProcedureReturn UnsignedToWord
EndProcedure
Procedure.l WordToUnsigned(Value.l)
Protected OFFSET_2 = 65536, MAXINT_2 = 32767
If Value < 0
WordToUnsigned = Value + OFFSET_2
Else
WordToUnsigned = Value
EndIf
ProcedureReturn WordToUnsigned
EndProcedure
OnErrorCall(@ErrorHandler())
Debug UnsignedToLong(3300000000)
Debug LongToUnsigned(-55)
Debug UnsignedToWord(45000)
Debug WordToUnsigned(-3000)
; You will get the following results:
; -994967296
; 4294967241
; -20536
; 62536
;Debug UnsignedToLong(-3300000000) ; this line results in an error due to negative input
Jim