- Joined
- Jan 2, 2020
- Messages
- 1,414
For everyone who deals with bits and got confused about the Shr resemblence like I did as a X64 hobbyist programmer,
this one's for you!
3 demos : Simple shift, logic shift, and signed math using only recursive logic
Hope someone will enjoy this!
this one's for you!
3 demos : Simple shift, logic shift, and signed math using only recursive logic
Hope someone will enjoy this!
Cerberus:
Import mojo2
'
' in C/C++ >> usually means arithmetic shift when used with signed integers (otherwise logical shift).
' in JavaScript >> always means arithmetic shift (>>> being logical shift).
'
Function Main()
New Game
Return 0
End
Class Game Extends App
Field canvas:Canvas
Field b:Int
Method OnCreate()
canvas = New Canvas()
SetSwapInterval 1 ; SetUpdateRate 0
' Local b:Int
b = -65535 ' 11111111111111110000000000000001 in 2's complement
' DEMO 1 (Arithmetical shift)
b = b Shr 1 ' Arithmetic shift! (this has nothing to do with the assembly instruction Shr, but Sar. It's just short for Shift right)
Print b ' Outputs -32768 which is 11111111111111111000000000000000 in 2's complement
' DEMO 2 (Logical shift)
b = b & $7fffffff ' Force logical shift! (by inserting zero on leftmost side)
Print b ' Outputs 2147450880 which is 01111111111111111000000000000000 in 2's complement
' DEMO 3 (Addition and subtraction using only logic)
Print addsub(10000,-1000) ' Outputs 9000
Return 0
End
Method OnUpdate()
If KeyHit(KEY_ESCAPE) Then OnClose()
Return 0
End
Method OnRender()
canvas.Clear
canvas.Flush
Return 0
End
Function addsub:Int(a:Int,b:Int)
If b = 0 Then Return a Else Return addsub(a ~ b, (a & b) Shl 1)
End
End
Last edited: