I am working through Leetcode's problem 191: Number of 1 Bits, and am confused as to a certain aspect of the solution. Here is the question:
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
And here is my (correct) solution:
func hammingWeight(num uint32) int {
c := 0
for num > 0{
if num%2==1{
c++
}
num/=2
}
return c
}
My question is twofold:
Does the program read input such as 0001101 as a binary number, and if so, why? I assumed that for a uint32 parameter, it would read it in decimal by default.
When shifting over to the right, why do we use /2 instead of /10?
I am still trying to wrap my head around the basic bit manipulation stuff, so this is still confusing me. If you take 0001101 and int divide it by 2, you would get 550, not 110. But if you take the same number and int divide it by 10, you would get 110. Why is /2 correct?
Thanks in advance
Related
This might be a really simple question for some, but I'm new to C++ and hope someone can answer this for me.
I'm using this online C++ compiler. Here's the simple code I'm running in it:
int main()
{
int x = 1- 2;
std::cout << x << std::endl;
return x;
}
The output is:
-1
...Program finished with exit code 255
Press ENTER to exit console.
That really ponders me. Why would the main() function return 255 when the value of x is -1?
Doesn't main() return an int (not an unsigned int), so it should be able to return a negative number, right?
How does -1 get converted to 255? Something to do with an 8-bit variable? But isn't the int type 16-bit?
This is not related to C language really. The operating system, or possibly just the C runtime (the small piece of the code which sets up things for your C program and actually calls your main function) limits exit code of the program to unsigned 8 bit number.
Very nearly all systems today use two's complement representation for negative numbers, and then bit pattern for -1 is having all bits of the number to be 1. Doesn't matter how many bits, they are all set when value is -1.
The simplest way to convert an int to 8 bit number is to just take 8 lowest bits (which are now all 1 as per above), so you end up with binary number:
11111111
If interpreted as unsigned, then in decimal value of this happens to be 255 (as signed 8 bits it is still -1), which you can check with any calculator which supports binary (such as Windows 10 Calculator app when you switch it to Programmer mode).
Looking at this from the opposite direction: When trying to understand funny numbers related to computers or programming, it is often useful to convert them to binary. If you convert 255 to binary, you get 11111111, and then if you know binary numbers, you should realize this is -1 if interpreted as signed 8 bit number.
I'm trying to write a function that takes 8 bits from an array that is 6x24 (just consider it taking a byte 1 bit at a time) and convert it to a decimal integer. Meaning there should be 18 numbers in total. Here is my code
int bitArray[6][24]; //the Array of bits, can only be a 1 or 0
int ex=0; //ex keeps track of the current exponent to use to calculate the decimal value of a binary digit
int decArray[18]; //array to store decimals
int byteToDecimal(int pos, int row) //takes two variables so you can give it an array column and row
{
numholder=0; //Temporary number for calculations
for(int x=pos; x<pos+8;x++) //pos is used to adjust where we start and stop looking at 1's and 0's in a row
{
if(bitArray[row][x] != 0)//if the row and column is a 1
{
numholder += pow(2, 7-ex);//2^(7-ex), meaning the first bit is worth 2^7, and the last is 2^0
}
ex++;
}
ex=0;
return numholder;
}
Then you can call the function like so
decArray[0]=byteToDecimal(0,0);
decArray[1]=byteToDecimal(8,0);
decArray[2]=byteToDecimal(16,0);
decArray[3]=byteToDecimal(0,1);
decArray[4]=byteToDecimal(8,1);
decArray[5]=byteToDecimal(16,1);
ect. When I place a single 1 into bitArray[0][0], calling the function gives me the number 127, when it should be 128.
Apparently bitArray (or at least the bytes involved) is not filled with zeros. The reason for that may vary. Most likely you have some leftover from previous operations with it. The second (insane) reason is that maybe Arduino C compiler doesn't initialize static objects with zeros (I've hever had experience with Arduino so I can't tell for sure).
In any case, try to call memset(bitArray, 0, sizeof(bitArray)) before you perform other operations with it.
Here is a demo written in plain C, demonstrating that normally your code should work fine.
After searching the net I came to know that the bit-wise version of the sieve of eratosthenes is pretty efficient.
The problem is I am unable to understand the math/method it is using.
The version that I have been busy with looks like this:
#define MAX 100000000
#define LIM 10000
unsigned flag[MAX>>6]={0};
#define ifc(n) (flag[n>>6]&(1<<((n>>1)&31))) //LINE 1
#define isc(n) (flag[n>>6]|=(1<<((n>>1)&31))) //LINE 2
void sieve() {
unsigned i, j, k;
for(i=3; i<LIM; i+=2)
if(!ifc(i))
for(j=i*i, k=i<<1; j<LIM*LIM; j+=k)
isc(j);
}
Points that I understood (Please correct me if I am wrong):
Statement in line 1 checks if the number is composite.
Statement in line 2 marks the number 'n' as composite.
The program is storing the value 0 or 1 at a bit of an int. This tends to reduce the memory usage to x/32. (x is the size that would have been used had an int been used to store the 0 or 1 instead of a bit like in my solution above)
Points that are going above my head as of now :
How is the finction in LINE 1 functioning.How is the function making sure that the number is composite or not.
How is function in LINE 2 setting the bit.
I also came to know that the bitwise sieve is timewise efficient as
well. Is it because of the use of bitwise operators only or
something else is contributing to it as well.
Any ideas or suggestions?
Technically, there is a bug in the code as well:
unsigned flag[MAX>>6]={0};
divides MAX by 64, but if MAX is not an exact multiple of 64, the array is one element short.
Line 1: Let's pick it apart:
(flag[n>>6]&(1<<((n>>1)&31)))
The flag[n>>6] (n >> 6 = n / 64) gives the 32-bit integer that holds the bit value for n / 2.
Since only "Odd" numbers are possible primes, divide n by two: (n>>1).
The 1<<((n>>1)&31) gives us the bit corresponding to n/2 within the 0..31 - (& 31 makes sure that it's "in range").
Finally, use & to combine the value on the left with the value on the right.
So, the result is true if element for n has bit number n modulo 32 set.
The second line is essentially the same concept, just that it uses |= (or equal) to set the bit corresponding to the multiple.
Hi i'm new to c++ so i'm not sure if this is a really silly question. Basically i'm using a c++ custom action project to interact with my MSI installer. I get a property that my user will have entered, it is an integer. I need to ensure that this is a multiple of 8 and i'm not sure how to go about this. Obviously if it can be divided by 8 it is a multiple but I am not sure how to capture if there is a remainder. Any help would be appreciated or even point me in the right direction. Thanks
Use the "modulo" operator, which gives the remainder from division:
if (n % 8 == 0) {
// n is a multiple of 8
}
Use the "modulo" or "integer remainder operator" %:
int a = ....;
if (a % 8 == 0 ) {
// a is amultiple of 8
}
use operator %
if ( num % 8 == 0 )
{
// num is multple of 8
}
Checking only the last 3 digits of a number does the job.
Even if you are given a huge number in the form of a string where the % operating is not useful you can check if only the last 3 digits are divisible by 8 then the whole number is divisible by 8.
For unsigned integers the three least significant bits are always zero for a multiple of 8, so a bitwise & on these bits should be false. For signed (twos complement) this is only true if the integer is positive, so beware if your input is being stored as signed or not (do you want to accept negative numbers as input). Also note the three least significant bits are zero for zero itself, so think if you want your check to be true when someone inputs zero. From your question it doesn't seem like your code has to be optimized so just use modulo.
I saw someone was using bit operation
bool f( int x){
return !(x & 7);
}
It was said this approach has some problem, but I am not quite sure.
I hope this finds you well.
I am trying to convert an index (number) for a word, using the ASCII code for that.
for ex:
index 0 -> " "
index 94 -> "~"
index 625798 -> "e#A"
index 899380 -> "!$^."
...
As we all can see, the 4th index correspond to a 4 char string. Unfortunately, at some point, these combinations get really big (i.e., for a word of 8 chars, i need to perform operations with 16 digit numbers (ex: 6634204312890625), and it gets really worse if I raise the number of chars of the word).
To support such big numbers, I had to upgrade some variables of my program from unsigned int to unsigned long long, but then I realized that modf() from C++ uses doubles and uint32_t (http://www.raspberryginger.com/jbailey/minix/html/modf_8c-source.html).
The question is: is this possible to adapt modf() to use 64 bit numbers like unsigned long long? I'm afraid that in case this is not possible, i'll be limited to digits of double length.
Can anyone enlight me please? =)
16-digit numbers fit within the range of a 64-bit number, so you should use uint64_t (from <stdint.h>). The % operator should then do what you need.
If you need bigger numbers, then you'll need to use a big-integer library. However, if all you're interested in is modulus, then there's a trick you can pull, based on the following properties of modulus:
mod(a * b) == mod(mod(a) * mod(b))
mod(a + b) == mod(mod(a) + mod(b))
As an example, let's express a 16-digit decimal number, x as:
x = x_hi * 1e8 + x_lo; // this is pseudocode, not real C
where x_hi is the 8 most-significant decimal digits, and x_lo the least-significant. The modulus of x can then be expressed as:
mod(x) = mod((mod(x_hi) * mod(1e8) + mod(x_lo));
where mod(1e8) is a constant which you can precalculate.
All of this can be done in integer arithmetic.
I could actually use a comment that was deleted right after (wonder why), that said:
modulus = a - a/b * b;
I've made a cast in the division to unsigned long long.
Now... I was a bit disappointed, because in my problem I thought I could keep raising the number of characters of the word with no problem. Nevertheless, I've started to get size issues at the n.ยบ of chars = 7. Why? 95^7 starts to give huge numbers.
I was hoping to get the possibility to write a word like "my cat is so fat I 1234r5s" and calculate the index of this, but this word has almost 30 characters:
95^26 = 2635200944657423647039506726457895338535308837890625 combinations.
Anyway, thanks for the answer.