How to test if a Short is negative?
BlitzMax Forums/BlitzMax Beginners Area/How to test if a Short is negative?
| ||
If I have a variable of type Short - how can I check it is negative? I thought I could cast it to an int, but this doesn't work e.g. Local s:short=-10 If int(s)<0 then ........ I don't really know what shorts are - but Box2d uses them for Filterdata - so I have to use them. Thanks for any help. |
| ||
A short is an unsigned integer - different to an Int, in that it comprises 16 bits (two bytes) instead of 32 bits (4 bytes). It cannot hold negative values. The only way (I can think of) to check if it should actually be negative, is to establish a maximum value that it can hold, say, 2000. That way you'll know that anything higher than 2000 is actually supposed to be negative. I don't know what this "box2d filterdata" lark is all about but if you want to use negative values, then short types are not the tool for the job. |
| ||
Something like :If s & $8000 Then ... End If should work for negative values of a short. |
| ||
If the system you're using it with uses signed shorts, then it probably works similar to signed integers, where the top bit determines that the number is negative. |
| ||
I once had a go at learning assembly language - you had to use a system like that for representing negative numbers - might have been called one or two's complement (it was a long time ago....) Thanks Brucey - that works nicely. BTW I'm doing it so I can use the default ShouldCollide method in Box2D and alter it a bit - the one that is in the help documentation - however the bit where it checks the GroupIndexes is wrong because it fails for negative group indexes - because it isn't checking for negative shorts in the right way This section: If filter1.GetGroupIndex() = filter2.GetGroupIndex() And filter1.GetGroupIndex() <> 0 Then return filter1.GetGroupIndex() > 0 End If I thought you might want to alter the helpfile. Thanks. |
| ||
Sorry, but for my own ref. what does If s & $8000 Then ... End If actually do? cheers |
| ||
returns zero if the number is positive, and not-zero if it is negative... assuming that "s" is of type Short. |
| ||
It masks away all bits but the sign, as the sign is stored in the last bit. This is how bitwise and works: 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1 so $8000 = %1000000000000000 (16 bits) |
| ||
..and explained more succinctly by grable ;-) |
| ||
Lol, thanks guys, now i gets it :-D |