WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Number Conversion

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Two complement of a Decimal

 Keywords: two's two complement representation Decimal Integer Dec2TwosComp UDF 

In the two's complement representation, the most significant bit is treated as the sign bit. When that bit is 1 the number is negative when viewed as a decimal signed integer. When the same two's complement integer is viewed as an unsigned decimal number, it just becomes a very large integer value because the sign bit is treated as just another digit.

WinBatch always displays integer values as signed but that does not change the integer representation in memory nor does it affect the results of WinBatch bitwise operations on that integer.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Returns the two's complement representation of a decimal integer
;; as a string of 1's and 0's.
#DefineFunction Dec2TwosComp( nDecInt )
        strReturn = ""
        For i = 31 To 0  By -1
           If nDecInt & (1<<i) Then strReturn = strReturn:'1'
           Else strReturn = strReturn:'0'
        Next
        Return strReturn
#EndFunction

;; Test
nDecimal = -16
strTwosComp = Dec2TwosComp(nDecimal)

Message("Two's Complement Representation", "Decimal: ":nDecimal:@CRLF:"Two's complement: ":strTwosComp)

More fun with the two's complement of a number (or negating a number the hard way.)

x = 16
y = (x ^ -1) + 1
Message("Two's Complement", "Two's complement of ":x:" is ":y)

The following article gives a nice explanation of how integers are handled on a computer and in various programming languages: http://en.wikipedia.org/wiki/Integer_(computer_science)


Article ID:   W18509
Filename:   Two complement of a Decimal.txt
File Created: 2014:07:24:10:55:22
Last Updated: 2014:07:24:10:55:22