Hello all,
Is this even at all possible?
How would I truncate zeros?
In the integer withOUT using any masking techniques (NOT ALLOWED: 0x15000000 & 0xff000000 like that.). And also WITHOUT any casting.
Hello all,
Is this even at all possible?
How would I truncate zeros?
In the integer withOUT using any masking techniques (NOT ALLOWED: 0x15000000 & 0xff000000 like that.). And also WITHOUT any casting.
The easiest way is to convert the int to a byte, so you are now down to 8 bits, so not everything is truncated, necessarily, but it would have fewer zeroes.
I am hoping this isn't for homework, but because I fear it is, giving you all the code would not be fair.
Well, really, if you want to truncate the right side, the naive solution is:
uint input = 0x150000;
if(input)
{
while(!(input & 0x01)) // Replace with while(!(input % 0x10)) if you are actually against masking.
{
input >>= 1;
}
}
// input, here, will be 0x15.
Though, you can unroll this loop. As in:
if(!(input & 0xFFFF)) { input >>= 16; }
if(!(input & 0x00FF)) { input >>= 8; }
if(!(input & 0x000F)) { input >>= 4; } // Comment this line, down, if you want to align on bytes.
if(!(input & 0x0003)) { input >>= 2; } // Likewise here, down, to align on nybbles.
if(!(input & 0x0001)) { input >>= 1; }
One way to do it without any masking (assuming you want to truncate zero bits):
int input = 0x150000;
while (input && !(input%2))
input >>= 1;
Here's a complete program which illustrates it.
#include <stdio.h>
int main (int argc, char *argv[]) {
int input = 0;
if (argc < 2) {
fprintf (stderr, "Needs at least one parameter.\n");
return 1;
}
input = atoi (argv[1]);
printf ("%x -> ", input);
while (input && !(input%2))
input >>= 1;
printf ("%x\n",input);
return 0;
}
If you want to truncate zero nybbles, use:
while (input && ((input%16)==0))
input >>= 4;
John Gietzen's answer is my favourite, but for fun, it can actually be done without a loop!
If you know how many trailing zeros there are, then you can just shift right that number of bits. There are a number of techniques for finding the number of bits. See the few sections following the linear algorithm here: http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear.
Divide by 16 (one nybble or hex digit's worth), as long as it's a multiple of 16:
if ( number )
while ( number % 16 == 0 )
number /= 16;
Of course, you can drop the initial test for zero if you know you'll never that as input.
Does this count as masking?
unsigned int truncate(unsigned int input)
{
while (input != 0 && input % 0x10 == 0)
{
input /= 0x10;
}
return input;
}