Recent

Author Topic: Algorithm for negative offset  (Read 228 times)

LemonParty

  • Full Member
  • ***
  • Posts: 142
Algorithm for negative offset
« on: February 17, 2025, 06:00:20 pm »
Let's say I have a negative number. I searching for algorithm that work like this:
If number -31, return 0;
If number -32, return -32;
If number -63, return -32;
If number -64, return -64;
If number -65, return -64;
And so on. Is there any fast bitwise operations for that?

Nimbus

  • New Member
  • *
  • Posts: 20
Re: Algorithm for negative offset
« Reply #1 on: February 17, 2025, 06:40:51 pm »
Can be done with bit shifts I guess, smth like
Code: Pascal  [Select][+][-]
  1. Result := -(-X shr 5) shl 5;
https://www.onlinegdb.com/tyME4tkHW

assuming X is a negative integer. Shifting by 5 as log2(32) = 5.

Or with a mask
Code: Pascal  [Select][+][-]
  1. Result := -(-X and (not 31));
« Last Edit: February 17, 2025, 06:49:20 pm by Nimbus »

LemonParty

  • Full Member
  • ***
  • Posts: 142
Re: Algorithm for negative offset
« Reply #2 on: February 18, 2025, 11:30:25 am »
Thank you, Nimbus.

 

TinyPortal © 2005-2018