Home AMX User Forum NetLinx Studio

Unsigned but negative?

If anyone can explain the following behaviour I'd be very grateful.
stack_var long var_long
stack_var slong var_slong

var_slong = -1000
var_long = type_cast(var_slong)
send_string 0, "'var_slong = ', itoa(var_slong)"
send_string 0, "'var_long = ', itoa(var_long)"
The code produces this output:
Line      6 (18:34:25)::  var_slong = -1000
Line      7 (18:34:25)::  var_long = -1000
Now forgive me for being picky but isn't one of the points of an unsigned data type that it is, in fact, unsigned? Testing (var_long < 0) gives the expected result of zero, but even so...

Plain old integers produce the expected result - the type cast results in the decimal value of the two's complement representation of the negative number.

Just wondering if anyone has experienced anything similar, or can explain what's going on.

Andy

Comments

  • ericmedleyericmedley Posts: 4,177
    Welcome to the bizzaro world of Netlinx variables.
  • a_riot42a_riot42 Posts: 1,624
    Oops! Don't do that!
    Paul
  • I suspect it may just be an issue with the display (although how, I have no idea). I stumbled across this when converting a slong to a 4-byte char array for sending to a piece of equipment. The bitwise operators don't like signed values so I type_cast to long before extracting each byte. It seems to work fine across the required range of input values.
    define_function char[4] IntToChar(slong num)
    {
        stack_var long cast_num
        stack_var char obj[4]
    
        cast_num = type_cast(num)
        for (n = 4; n; n--) {
            obj[n] = type_cast(cast_num >> ((4 - n) * 8))
        }
    
        return obj
    }
    
    I'll just sweep the minus sign under the NetLinx carpet and move on.

    Andy
  • DHawthorneDHawthorne Posts: 4,584
    There are a fair number of under-the-hood conversions in NetLinx, no doubt from overloaded functions we have no access to. My habit is to be very explicit with type casts and assignments so that every variable is exactly what I expect it to be going in, so there are no surprises coming out.
  • jweatherjweather Posts: 320
    It sounds like you already understand what's happening from your comment about integers working the way you expected. The missing piece here is that ITOA doesn't care what type its argument is, it's casting it to SLONG (see the help file). Whether you call itoa(-1000) or itoa(4294966295) you'll get out -1000 because it's expecting a signed value.
  • Thanks to jweather for sorting out that little mystery. I simply never thought to account for any effect that itoa might have on the values concerned!

    Andy
  • a_riot42a_riot42 Posts: 1,624
    ATOI is also kind of funny in that it returns 0 if no valid characters are found. But it will also return 0 if you do atoi('0').
    Paul
Sign In or Register to comment.