Bitshifting/truncating on Max integers?

    Mar 31 2013 | 8:02 am
    So, I have what appears to be a strange problem - I need to truncate the top 7 bits of a 10 bit number, so that I'm left with just 3 bits.
    In pseudo-arduino, I would do this like this:
    uint16_t X = y << 13 >> 13;
    The top 13 bits of the 16 bit integer (though it only ever reaches 10-bit values) are discarded, and then shifted back and replaced with zeroes - leaving me a 3-bit number in a 16-bit shell.
    I've tried numerous attempts at this using the max bitshift operators, but none of them seem to work the way I'd expect them to. Possibly because max only seems to deal with signed integers?
    Anyone have any thoughts on this?

    • Mar 31 2013 | 9:50 am
      Yes, Max's integers are always signed. Moreover, shifting back and forth relies on not-so-safe assumptions about the size of integers (32-bit until max 6.0.x, 64-bit in Max 6.1 64 bits). To retain the n less significant bits of an integer, you can use bitwise and 2ˆn-1 - in your case [& 7]. For positive numbers, modulo 2ˆn ([% 8]) will give you the same result.
      hth aa
    • Mar 31 2013 | 12:20 pm
      Thanks - that's actually what I'd been using, but apparently I shouldn't be doing this stuff at 3am, as for some reason it was striking me as doing the wrong thing - just tested it out (connected it up), works as expected. Thanks!