Page 1 of 1
in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 9:09 am
by Adversus
I have two integer alpha values and I want to set the first four bits of a byte to one and the second 4 bits of the byte to the second alpha.
I think I need to use bitwise operators but can't figure it out. Does anyone else know how?
Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 10:16 am
by greenya
Code: Select all
int varResult = 0;
int varWith4bitsHI = 0xa;
int varWith4bitsLO = 0xb;
varResult = varWith4bitsHI << 4 | varWith4bitsLO;
// now varResult == 0xab
Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 10:26 am
by hendu
value = secondalpha;
value |= 15;
@greenya
0xb would be 11 in decimal or 1011 in binary, not all four 1111 = 15 = 0xf
Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 10:36 am
by Adversus
thanks, what would be the functions for adding and getting them individually?
Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 11:30 am
by greenya
hendu wrote:@greenya
0xb would be 11 in decimal or 1011 in binary, not all four 1111 = 15 = 0xf
Didn't understand you.
4 bits is 1111 and value range is 0-15 inclusive.
8 bits makes byte.
In my post i showed how individually set first 4 bits and last 4 bits.
Adversus wrote:thanks, what would be the functions for adding and getting them individually?
Refering to my code above, you can do that next way:
Code: Select all
int varResult11110000 = (varResult & 0xf0) >> 4; // now its 0xa
int varResult00001111 = varResult & 0xf; // now its 0xb
Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 11:56 am
by hendu
Yep, but he asked for all 4 low bits set

Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 5:30 pm
by Mel
the bitwise operations that may help are the shift left and shift right ops. But i never remember how they work exactly, and leads me to errors sometimes, the good thing is that both have an equivalent in multiplying or dividing a number by the power of 2 you want to shift the bits, if you want to store your alpha values, this would work pretty well:
combinedAlpha = alpha1*16 + alpha2;
if you want to recover your original alphas:
alpha1 = combinedAlpha/16;
alpha2 = combinedAlpha%16;
and you are done. With integer values they are as fast as the bitwise operations. Just keep in mind that your combined alpha should be treated as an unsigned char.
Re: in c++ how do you set the first 4 bits in a byte
Posted: Thu Jul 05, 2012 5:50 pm
by zerochen
or u use something like this
Code: Select all
void setBit(int& val, int bitToSet)
{
val |= 1<<bitToSet;
}
bool isBitSet(int& val, int bitToTest)
{
return (1<<bitToTest) == (val && 1<<bitToTest);
}
Re: in c++ how do you set the first 4 bits in a byte
Posted: Wed Jul 11, 2012 12:53 pm
by Adversus
Thanks, bit help. I think I even understand what that does
