Given an integer x, how would you return an integer y that is lower than or equal to x and a multiple of 64?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Simply
andit with the bit inversion of (64-1):This basically clears out the lower six bits which is the same as rounding it down to a multiple of 64. Be aware that this will round towards negative infinity for negative numbers, not towards zero, but that seems to be what your question requires.
You can see the behaviour here in this multiple-of-four variant:
This produces:
Keep in mind this only works for powers of two (like 26 = 64) and two’s complement (the ISO standard doesn’t mandate that representation – see here for details – but I’ve never seen an C environment that doesn’t use it and I’ve worked on systems from the puniest 8051 to the largest mainframes). If you want to use any other number for the divisor, you should probably use the proper math functions like
floor.