| View previous topic :: View next topic |
| Author |
Message |
jballi
Joined: 01 Oct 2005 Posts: 748 Location: Texas, USA
|
Posted: Fri Jan 22, 2010 3:05 am Post subject: [Tip] Convert UInt to Int (and other conversion tips) |
|
|
A couple of things... First of all, this topic is a bit out of my pay scale but I'm posting anyway because the information has helped me. Next, posting tips in this forum is a fool's errand but I guess I'm doing it anyway.
I found an obscure post from Sean who shared a trick for converting a UShort (unsigned 16-bit integer) to Short (signed integer) in one simple step:
| Code: | | x:=x<<48>>48 ;-- Convert UShort to Short |
No if/then/else statements. No ternary operations. Just simple bit shifting. This conversion is valuable because a few of the older messages and WinAPI functions still return values in 16-bit variables and sometimes they need to be converted. Thanks Sean for the tip. The original post can be found here.
What I need more often is a conversion from UInt (unsigned 32-bit integer) to Int (signed 32-bit integer). The most common method (which I've been using for a while) is published in the Autohotkey help file. The conversion looks something like this:
| Code: | | x:=x > 0x7FFFFFFF ? -(~x) - 1 : x |
I stumbled on a simpler method using bit shifting:
| Code: | | x:=x<<32>>32 ;-- Convert UInt to Int |
I would like to take credit for this tip but someone else probably published it earlier. I just couldn't find it!
There you have it. If you have any other conversion tips or if you find any problems with this code, please post! |
|
| Back to top |
|
 |
Sean
Joined: 12 Feb 2007 Posts: 2462
|
|
| Back to top |
|
 |
Guest
|
Posted: Sat Jan 23, 2010 3:48 pm Post subject: |
|
|
| Sean could you elaborate? How is that different than "normal"?...(if bit shifting isn't an "arithmetic shift" what is it?)...is it a good thing AutoHotkey does it this way or a bad thing/bug? If "bit shift (right)" is an "arithmetic shift" then what is "bit shift (left)"?...both in AutoHotkey & in whatever is "normal"... |
|
| Back to top |
|
 |
Sean
Joined: 12 Feb 2007 Posts: 2462
|
Posted: Sat Jan 23, 2010 5:11 pm Post subject: |
|
|
Another possibility is the so called logical bit shift, which is mentioned in the last part of the thread linked in my previous post. Left bit shifts are indentical for both arithmetic and logical, so are of no concern in the case of bit shift. IMO, arithmetic bit shift is the natural choice for signed integers.
In general, whether to respect the sign bit or not will always be a crucial decision, not only for contraction but also for expansion. |
|
| Back to top |
|
 |
|