C++ - Right shift not evaluated correctly inside IF [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following piece of code,
if (index > ((v.size() >> 1) - 1)) { }
v.size() is 0 and index is 1. The execution does not get into the if block. But if I change the above code to,
int limit = (v.size() >> 1) - 1;
if (index > limit) { }
and with the same values of v.size() and index, the execution does get into the if block.
Why does this behavior happen? Thanks.

You are obviously performing unsigned comparison. The return type of v.size() is likely size_t, which is an unsigned integer. Thus, the expression (v.size() >> 1) - 1 yields the largest possible unsigned integer. Unless you convert that back to a signed integer type, you won't get positive comparison results.
A simple cast to ssize_t before the subtraction will fix your problem:
if (index > (((ssize_t)v.size() >> 1) - 1)) { }
I have used ssize_t because that type is guaranteed to be able to hold any size_t value, reinterpreting it to negative if its most significant bit is set. That cannot be said for int, as that is usually only 32 bits on 64 bit platforms. So, using int as you did in your second example, may cut off some bits.

Related

Check whether the number has alternating bits?

I have come across the question in leetcode on checking whether the number has alternative bits or not ?. Clear explanation of the question is given below. And this question is solved in stack overflow too. Stackoverflow Solution.
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.Leetcode Question
I know how to solve the question using for loop by checking whether two bits are same or not (i.e previous bit and the present bit is same or not). But i was intrigued by the below solution in leetcode
(n & (n >> 1)) == 0 && (n & (n >> 2)) == (n >> 2)
I am concerned about the understanding behind this one line code. Examples please !!
Lets start with n & (n >> 1) == 0: if the bits are alternating, then there would be 0 overlap, and so & would return 0.
The second part makes sure that the bits aren't all 0 and ensures the last bits which are discarded with the shift are still consistent

How do I safely convert a double into an integer in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is there a way to convert a double into an integer without risking any undesired errors in the process? I read in Programming - Principles and Practice Using C++ (a book written by the creator of c++) that doubles cannot be turned into integers, but I've put it to the test, and it converts properly about 80% of the time. What's the best way to do this with no risk at all, if it's even possible?
So for example, this converts properly.
double bruh = 10.0;
int a = bruh;
cout << bruh << "\n";
But this doesn't.
double bruh = 10.9;
int a = bruh;
cout << bruh << "\n";
In short, it doesn't round automatically so I think that's what constitutes it as "unsafe".
It it not possible to convert all doubles to integers with no risk of losing data.
First, if the double contains a fractional part (42.9), that fractional part will be lost.
Second, doubles can hold a much larger range of values than most integers, something around 1.7e308, so when you get into the larger values you simply won't be able to store them into an integer.
way to convert a double into an integer without risking any undesired errors
in short, it doesn't round automatically so I think that's what constitutes it as "unsafe"
To convert to an integer value:
x = round(x);
To convert to an integer type:
Start with a round function like long lround(double x);. It "Returns the integer value that is nearest in value to x, with halfway cases rounded away from zero."
If the round result is outside the long range, problems occur and code may want to test for that first.
// Carefully form a double the is 1 more than LONG_MAX
#define LONG_MAXP1 ((LONG_MAX/2 + 1)*2.0)
long val = 0;
if (x - LONG_MAXP1 < -0.5 && x - LONG_MIN > -0.5) {
val = lround(x);
} else {
Handle_error();
}
Detail: in order to test if a double is in range to round to a long, it is important to test the endpoints carefully. The mathematical valid range is (LONG_MIN-0.5 ... LONG_MAX + 0.5), yet those endpoints may not be exactly representable as a double. Instead code uses nearby LONG_MIN and LONG_MAXP1 whose magnitudes are powers of 2 and easy to represent exactly as a double.

Understanding binary conversion implementation in C++ with bit operations [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am interested in understanding the implementation of converting decimal to binary. Could somebody clarify the purpose of using left-shift and Right-shift in the following code?
void static inline unsignedToBinary(unsigned x, char*& bin)
{
bin = (char*) malloc(33);
int p = 0;
for (unsigned i = (1 << 31); i > 0; i >>= 1)
bin[p++] = ((x&i) == i) ? '1' : '0';
bin[p] = '\0';
}
This is a straightforward implementation of binary conversion that uses bit operations.
Variable i represents the mask - an int containing 2k value, where k is the position of the bit.
The initial value is 231, produced with left-shifting 1 by 31.
for loop uses >>= 1 to right-shift the mask until 1 gets shifted out of it, making i == 0.
At each iteration x&i is compared to i. The comparison succeeds when x contains 1 in the position where i has its 1; it fails otherwise.
Note: Although using malloc in C++ is certainly allowed, it is not ideal. If you want to stay with C strings, use new char[33] instead. A more C++-like approach would be using std::string.

Finding parity of number of '1's in a int variable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Given an int variable, I would like to check if the number of '1' in its binary representation is even or odd. It can be made with xor operations like
int n;
int s = 0;
for(;n;n>>=1)
s ^= (n&1);
There's some better way to do so in C++?
Note: I'm not asking for the number of '1's, but for its parity, so I thought there could be some better code than mine.
uint32_t v = somevalue;
v ^= v >> 1;
v ^= v >> 2;
v = (v & 0x11111111U) * 0x11111111U;
bool parity = (v >> 28) & 1;
From https://graphics.stanford.edu/~seander/bithacks.html
It has a 64bit variant too.
For clarification, with "parity" I don't mean if the number is even or odd mathematically, but if the count of 1 bits in it's binary representation is even or odd; like described in https://en.wikipedia.org/wiki/Parity_bit. With the maths meaning, the code in the question makes no sense, so I assumed OP means the same. The statement
I'm not asking for the number of '1's, but for its parity
then means that he/she just wants to know if the 1 count is even or odd,
but not the exact number of 1's.
If you are really after speed, you can tabulate the number of bits (or just its parity) for all byte values 0..255. Then mapping a union on the variable or using shifts/masks, accumulate for the four bytes.
Even faster and more paranoid, tabulate for all short values 0..65535.

Write a function to copy 0-15 bits into 16-31 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How to write a function to copy 0-15 bits into 16-31?
unsigned int n = 10; // 1010
copyFromTo(n);
assert(n == 655370);
n = 5;
copyFromTo(n);
assert(n == 327685);
n = 134;
copyFromTo(n);
assert(n == 8781958);
You want to copy the bits in 0-15 to 16-31. You should understand that multiplying by 2 is equivalent to shifting the bits of the number once to the left (moving to higher bits).
If your number is n, n << 16 would be shifting your number 16 bits to the left. This is equivalent to multiplying n with the 16th power of 2, which happens to be 65536.
To copy the bits, and keep the original bits in 0-15, the command n = n + (n << 16); should work. However, the issue with this is (as pointed out in the comments), that the upper 16-31 bits are still set in n + term. We also need to clear these bits. Note that 65535 corresponds to 2^16 - 1, and would have the first 0-15 bits as 1, and others as 0. So the correct command would be n = (n && 65535) + (n << 16);
This will do it:
void copyFromTo(unsigned int& n)
{
n = (n & 0xffff) * 0x00010001;
}
n << 16 to shift bits would do it, to move lower bits to upper? (edited) And after that, copying just the lower 16 bits into it