I wouldn't know of a "better way". Sounds like the right thing to do to me.
But are you sure you need the cast?
it may be nicer to use a unsigned char stuff.
I've been set a task, where I have an unsigned char (8bits - doh) which is not used as a char but as a container for some small ints.
Like this
00101100, now in ASM I would SHL or/and ROL the hell of these (fun for the whole family) but is there a safe way to shift fx. the 3 lowest bits out and store them in an int?
I would think C++ streams would help me, but my book mentions nothing like this.
Now we're going for safe, since this is a rather important bit of a very large system, I don't want to break shit trying to go fast.
I would think something like this:
might work, but it just doesn't look at all very fun, and it just sounds so unclean to AND and then cast the information, there has to be a better way.Code://this is our 8bit input char stuff; //this would be our mask, in this case the lower 4 bits // 8+4+2+1 unsigned short int mask = 15; //this is where we want the information to go unsigned short int container; container = static_cast<unsigned short int>(stuff & mask)
I wouldn't know of a "better way". Sounds like the right thing to do to me.
But are you sure you need the cast?
it may be nicer to use a unsigned char stuff.
I thought there was an easy way to shift bits in C++. I may be thinking of Java or something. But anyway, here are the ways I would do the equivelant assembler functions. n is how many bits to shift or rotate.
shl:
Multiply by 2 ^ n.
shr:
Divide by 2 ^ n.
rol:
Multiply by 2. Capture overflow error. (Is there a way to do this in C++? It may be necessary to use typecasting to save the results in a larger data type and test the value of the new number to see if it's greater than what your old data type would allow instead.) Add 1 if overflow. Do this n times.
ror:
Divide by 2. Modulus (the % operator) the old number by 2. Set the first bit of new number if remainder. (You can do this by adding or oring. It may be more convenient to do the modulus operation first.)
Multiplying / dividing by 2^n works but uses relatively much CPU.
In C/C++ there are special bitwise operators:
/* Shift 'b' by 'n' bit positions to the left: */
a = b << n;
/* shift to the right */
a = b >> n;
/* b AND m */
a = b & m;
/* b OR m */
a = b | m;
/* b XOR m */
a = b ^ m;
/* Bits of 'b' flipped */
a = ~b;
As far as I know there's no special operator for bitrotation.
Bookmarks