How do I flip part of number/bitset in C++ efficiently? - c++

Consider I have a number 100101 of length 6. I wish to flip bits starting from position 2 to 5 so my answer will be 111011. I know that I can flip individual bits in a loop. But is there an efficient way of doing this without a for loop?

If I understand you correctly, try
namespace {
unsigned flip(unsigned a)
{
return a ^ 0b011110u;
}
} // namespace
Just adjust the constant to the actual bits you want to flip by having them as 1's in the constant.
On the otherhand, if you need just to update an individual variable you also use
unsigned value = 0b100101u;
value ^= 0b011110u;
assert(value == 0b111011u);
EDIT
And here is the same using std::bitset<6u> and C++98:
#include <bitset>
#include <cassert>
int main()
{
std::bitset<6u> const kFlipBit2to6WithXor(0x1Eu); // aka 0b011110u
std::bitset<6u> number(0x25u); // aka 0b100101u
number ^= kFlipBit2to6WithXor;
assert(number.to_ulong() == 0x3Bu); // aka 0b111011u
return 0;
}

0b1111 is 0b10000-1.
constexpr unsigned low_mask(unsigned x){
return (1u<<x)-1;
}
0b1100 is 0b1111-0b11.
constexpr unsigned mask(unsigned width, unsigned offset){
return low_mask(width+offset)-low_mask(offset);
}
then use xor to flip bits.
unsigned result = 0b100001 ^ mask(4,2);

Related

Set the most significant bit

I'm trying to toggle the most significant bit of an unsigned int based on a bool flag. This is my code for an hypothetical K = unit64_t:
This is the Item class:
template<typename K>
class Item {
public:
K first;
Item() = default;
explicit Item(const K &elem, const bool flag = false) {
first = elem & 0x3FFFFFFFFFFFFFFF;
first |= (flag * 0x8000000000000000);
}
};
Is there a way to do this fully generical? That it works for all kind of numeric K?
I tried with the 8 * sizeof(K) but it doesn't work.
An option using only bit operations:
template<typename T>
void Item(T& elem, bool flag = false) {
T mask = (T)1 << (sizeof(T) * 8 - 1);
elem = (elem & ~mask) | (flag ? mask : 0);
}
You can leverage std::bitset for this. Not sure how well this optimizes, but it should optimize well and it will work generically and requires no bitwise operation knowledge.
template <typename T>
void toggle_msb(T& val)
{
constexpr auto bit_width = sizeof(T) * CHAR_BIT;
std::bitset<bit_width> temp(val);
val = temp.flip(bit_width - 1).to_ullong();
}
Using bitwise operations, but without explicitly depending on the size of T:
template<typename T>
T set_top_bit(T value, bool state) {
constexpr T mask = T(~T(0)) >> 1;
value &= mask;
if (state) value |= ~mask;
return value;
}
T(~T(0)) gets a T with all bits set1; >> 1 throws out the bottom bit getting a 0 in from the top, so in mask we have a T with all bit set but the topmost. Notice that all this dance is purely formal—this is all evaluated at compile time.
The rest is pretty much like your code: mask out the top bit from value and OR it back in depending on state (~mask will be a T with only the top bit set).
Plain ~0 would result in an int set to -1, ~0U in an unsigned int with all bits set; to obtain a T with all bits set, we need to flip the bits of a T(0) (so, a 0 of our T type), and also to cast back to T later, because, if T is smaller than int, ~T(0) is actually equivalent to ~int(T(0)), so ~0, due to integer promotion rules.
From this great post, How do you set, clear, and toggle a single bit?, you can use this branchless version:
#include <climits>
template<typename T>
constexpr T set_top_bit_v2(T value, bool state) {
constexpr auto msb = (sizeof(T) * CHAR_BIT) - 1;
return (value & ~(T{1} << msb)) | (T{state} << msb);
}
Comparing the output with the version of Matteo Italia on Godbolt (here), despite the differences Clang seems to generate the same code, while GCC and MSVC seem to emit less instructions when using this version.

Multiply 2 1000-digit binary numbers in C++ [duplicate]

I have the following code
int i, a, z;
i = 2343243443;
a = 5464354324324324;
z = i * a;
cout << z << endl;
When these are multiplied it gives me -1431223188 which is not the answer. How can I make it give me the correct answer?
The result overflows the int (and also std::uint64_t)
You have to use some BigInt library.
As Jarod42 suggested is perfectly okay, but i am not sure whether overflow will take place or not ?
Try to store each and every digit of number in an array and after that multiply. You will definitely get the correct answer.
For more detail how to multiply using array follow this post http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial
Use pan paper approach as we used in 2nd standard.
Store two numbers in two different array in reverse order. And take ans array as size of (arr1.size + arr2.size).And also initilize ans array to zero.
In your case
arr1[10]={3,4,4,3,4,2,3,4,3,2},
arr2[15]={4,2,3,4,2,3,,4,5,3,4,5,3,4,6,4,5};
for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{
ans[i+j]+=arr1[i]*arr2[j];
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
Then ans array contain the result.Please print carefully ans array. it may contain leading zero.
ints only hold 32 bits. When the result of a multiplication is larger than 2^31 - 1, the result rolls over to a large negative value. Instead of using the int data type, use long long int, which holds 64 bits.
You should first try to use 64-bit numbers (long or better, unsigned long if everything is positive). With unsigned long you can operate between 0 and 18446744073709551615, with long between -9223372036854775808 and 9223372036854775807.
If it is not enough, then there is no easy solution, you have to perform your operation at software level using arrays of unsigned long for instance, and overload "<<" operator for display. But this is not that easy, and I guess you are a beginner (no offense) considering the question you asked.
If 64-bit representation is not enough for you, I think you should consider floating-point representation, especially "double". With double, you can represent numbers between about -10^308 and 10^308. You won't be able to have perfectly accurate computatiosn on very large number (the least significant digits won't be computed), but this should be a good-enough option for whatever you want to do here.
First, you have to make your value long longs
Second, you would want to add a (long long) in front of the multiplication. This is because when you have (ab) it returns an int therefore if you want it to return a long long you would want (long long)(ab).
I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
//Numbers to be multiplied
long a=111,b=100;
//Convert them to strings (or character array)
string arr1 = to_string(a), arr2 = to_string(b);
//Reverse them
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
//Getting size for final result, just to avoid dynamic size
int ans_size = arr1.size() + arr2.size();
//Declaring array to store final result
int ans[ans_size]={0};
//Multiplying
//In a reverse manner, just to avoid reversing strings explicitly
for(int i=0; i<arr1.size();i++)
{
for(int j=0; j<arr2.size();j++)
{
//Convert array elements (char -> int)
int p = (int)(arr1[i]) - '0';
int q = (int)(arr2[j]) - '0';
//Excerpt from Shravan's answer above
ans[i+j]+=p*q;
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
//Declare array to store string form of final answer
string s="";
for(auto i=0;i<ans_size; ++i)
s += to_string(ans[i]);
reverse(s.begin(), s.end() );
//If last element is 0, it should be skipped
if(s[0] =='0')
{
string ss(s,1,s.size()-1);
s=ss;
}
//Final answer
cout<< s;
return 0;
}
Use float instead. It can go up to about 3.4028235 × 1038
// its may heplfull for you
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 1000
void reverse(char *from, char *to ){
int len=strlen(from);
int l;
for(l=0;l<len;l++)to[l]=from[len-l-1];
to[len]='\0';
}
void call_mult(char *first,char *sec,char *result){
char F[MAX],S[MAX],temp[MAX];
int f_len,s_len,f,s,r,t_len,hold,res;
f_len=strlen(first);
s_len=strlen(sec);
reverse(first,F);
reverse(sec,S);
t_len=f_len+s_len;
r=-1;
for(f=0;f<=t_len;f++)temp[f]='0';
temp[f]='\0';
for(s=0;s<s_len;s++){
hold=0;
for(f=0;f<f_len;f++){
res=(F[f]-'0')*(S[s]-'0') + hold+(temp[f+s]-'0');
temp[f+s]=res%10+'0';
hold=res/10;
if(f+s>r) r=f+s;
}
while(hold!=0){
res=hold+temp[f+s]-'0';
hold=res/10;
temp[f+s]=res%10+'0';
if(r<f+s) r=f+s;
f++;
}
}
for(;r>0 && temp[r]=='0';r--);
temp[r+1]='\0';
reverse(temp,result);
}
int main(){
char fir[MAX],sec[MAX],res[MAX];
while(scanf("%s%s",&fir,&sec)==2){
call_mult(fir,sec,res);
int len=strlen(res);
for(int i=0;i<len;i++)printf("%c",res[i]);
printf("\n");
}
return 0;
}
You can use queue data structure to find the product of two really big numbers with O(n*m). n and m are the number of digits in a number.

Cheking a pattern of bits in a sequence

So basically i need to check if a certain sequence of bits occurs in other sequence of bits(32bits).
The function shoud take 3 arguments:
n right most bits of a value.
a value
the sequence where the n bits should be checked for occurance
The function has to return the number of bit where the desired sequence started. Example chek if last 3 bits of 0x5 occur in 0xe1f4.
void bitcheck(unsigned int source, int operand,int n)
{
int i,lastbits,mask;
mask=(1<<n)-1;
lastbits=operand&mask;
for(i=0; i<32; i++)
{
if((source&(lastbits<<i))==(lastbits<<i))
printf("It start at bit number %i\n",i+n);
}
}
Your loop goes too far, I'm afraid. It could, for example 'find' the bit pattern '0001' in a value ~0, which consists of ones only.
This will do better (I hope):
void checkbit(unsigned value, unsigned pattern, unsigned n)
{
unsigned size = 8 * sizeof value;
if( 0 < n && n <= size)
{
unsigned mask = ~0U >> (size - n);
pattern &= mask;
for(int i = 0; i <= size - n; i ++, value >>= 1)
if((value & mask) == pattern)
printf("pattern found at bit position %u\n", i+n);
}
}
I take you to mean that you want to take source as a bit array, and to search it for a bit sequence specified by the n lowest-order bits of operand. It seems you would want to perform a standard mask & compare; the only (minor) complication being that you need to scan. You seem already to have that idea.
I'd write it like this:
void bitcheck(uint32_t source, uint32_t operand, unsigned int n) {
uint32_t mask = ~((~0) << n);
uint32_t needle = operand & mask;
int i;
for(i = 0; i <= (32 - n); i += 1) {
if (((source >> i) & mask) == needle) {
/* found it */
break;
}
}
}
There are some differences in the details between mine and yours, but the main functional difference is the loop bound: you must be careful to ignore cases where some of the bits you compare against the target were introduced by a shift operation, as opposed to originating in source, lest you get false positives. The way I've written the comparison makes it clearer (to me) what the bound should be.
I also use the explicit-width integer data types from stdint.h for all values where the code depends on a specific width. This is an excellent habit to acquire if you want to write code that ports cleanly.
Perhaps:
if((source&(maskbits<<i))==(lastbits<<i))
Because:
finding 10 in 11 will be true for your old code. In fact, your original condition will always return true when 'source' is made of all ones.

How can I multiply really big numbers c++

I have the following code
int i, a, z;
i = 2343243443;
a = 5464354324324324;
z = i * a;
cout << z << endl;
When these are multiplied it gives me -1431223188 which is not the answer. How can I make it give me the correct answer?
The result overflows the int (and also std::uint64_t)
You have to use some BigInt library.
As Jarod42 suggested is perfectly okay, but i am not sure whether overflow will take place or not ?
Try to store each and every digit of number in an array and after that multiply. You will definitely get the correct answer.
For more detail how to multiply using array follow this post http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial
Use pan paper approach as we used in 2nd standard.
Store two numbers in two different array in reverse order. And take ans array as size of (arr1.size + arr2.size).And also initilize ans array to zero.
In your case
arr1[10]={3,4,4,3,4,2,3,4,3,2},
arr2[15]={4,2,3,4,2,3,,4,5,3,4,5,3,4,6,4,5};
for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{
ans[i+j]+=arr1[i]*arr2[j];
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
Then ans array contain the result.Please print carefully ans array. it may contain leading zero.
ints only hold 32 bits. When the result of a multiplication is larger than 2^31 - 1, the result rolls over to a large negative value. Instead of using the int data type, use long long int, which holds 64 bits.
You should first try to use 64-bit numbers (long or better, unsigned long if everything is positive). With unsigned long you can operate between 0 and 18446744073709551615, with long between -9223372036854775808 and 9223372036854775807.
If it is not enough, then there is no easy solution, you have to perform your operation at software level using arrays of unsigned long for instance, and overload "<<" operator for display. But this is not that easy, and I guess you are a beginner (no offense) considering the question you asked.
If 64-bit representation is not enough for you, I think you should consider floating-point representation, especially "double". With double, you can represent numbers between about -10^308 and 10^308. You won't be able to have perfectly accurate computatiosn on very large number (the least significant digits won't be computed), but this should be a good-enough option for whatever you want to do here.
First, you have to make your value long longs
Second, you would want to add a (long long) in front of the multiplication. This is because when you have (ab) it returns an int therefore if you want it to return a long long you would want (long long)(ab).
I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
//Numbers to be multiplied
long a=111,b=100;
//Convert them to strings (or character array)
string arr1 = to_string(a), arr2 = to_string(b);
//Reverse them
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
//Getting size for final result, just to avoid dynamic size
int ans_size = arr1.size() + arr2.size();
//Declaring array to store final result
int ans[ans_size]={0};
//Multiplying
//In a reverse manner, just to avoid reversing strings explicitly
for(int i=0; i<arr1.size();i++)
{
for(int j=0; j<arr2.size();j++)
{
//Convert array elements (char -> int)
int p = (int)(arr1[i]) - '0';
int q = (int)(arr2[j]) - '0';
//Excerpt from Shravan's answer above
ans[i+j]+=p*q;
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
//Declare array to store string form of final answer
string s="";
for(auto i=0;i<ans_size; ++i)
s += to_string(ans[i]);
reverse(s.begin(), s.end() );
//If last element is 0, it should be skipped
if(s[0] =='0')
{
string ss(s,1,s.size()-1);
s=ss;
}
//Final answer
cout<< s;
return 0;
}
Use float instead. It can go up to about 3.4028235 × 1038
// its may heplfull for you
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 1000
void reverse(char *from, char *to ){
int len=strlen(from);
int l;
for(l=0;l<len;l++)to[l]=from[len-l-1];
to[len]='\0';
}
void call_mult(char *first,char *sec,char *result){
char F[MAX],S[MAX],temp[MAX];
int f_len,s_len,f,s,r,t_len,hold,res;
f_len=strlen(first);
s_len=strlen(sec);
reverse(first,F);
reverse(sec,S);
t_len=f_len+s_len;
r=-1;
for(f=0;f<=t_len;f++)temp[f]='0';
temp[f]='\0';
for(s=0;s<s_len;s++){
hold=0;
for(f=0;f<f_len;f++){
res=(F[f]-'0')*(S[s]-'0') + hold+(temp[f+s]-'0');
temp[f+s]=res%10+'0';
hold=res/10;
if(f+s>r) r=f+s;
}
while(hold!=0){
res=hold+temp[f+s]-'0';
hold=res/10;
temp[f+s]=res%10+'0';
if(r<f+s) r=f+s;
f++;
}
}
for(;r>0 && temp[r]=='0';r--);
temp[r+1]='\0';
reverse(temp,result);
}
int main(){
char fir[MAX],sec[MAX],res[MAX];
while(scanf("%s%s",&fir,&sec)==2){
call_mult(fir,sec,res);
int len=strlen(res);
for(int i=0;i<len;i++)printf("%c",res[i]);
printf("\n");
}
return 0;
}
You can use queue data structure to find the product of two really big numbers with O(n*m). n and m are the number of digits in a number.

Shortest way to calculate difference between two numbers?

I'm about to do this in C++ but I have had to do it in several languages, it's a fairly common and simple problem, and this is the last time. I've had enough of coding it as I do, I'm sure there must be a better method, so I'm posting here before I write out the same long winded method in yet another language;
Consider the (lilies!) following code;
// I want the difference between these two values as a positive integer
int x = 7
int y = 3
int diff;
// This means you have to find the largest number first
// before making the subtract, to keep the answer positive
if (x>y) {
diff = (x-y);
} else if (y>x) {
diff = (y-x);
} else if (x==y) {
diff = 0;
}
This may sound petty but that seems like a lot to me, just to get the difference between two numbers. Is this in fact a completely reasonable way of doing things and I'm being unnecessarily pedantic, or is my spidey sense tingling with good reason?
Just get the absolute value of the difference:
#include <cstdlib>
int diff = std::abs(x-y);
Using the std::abs() function is one clear way to do this, as others here have suggested.
But perhaps you are interested in succinctly writing this function without library calls.
In that case
diff = x > y ? x - y : y - x;
is a short way.
In your comments, you suggested that you are interested in speed. In that case, you may be interested in ways of performing this operation that do not require branching. This link describes some.
#include <cstdlib>
int main()
{
int x = 7;
int y = 3;
int diff = std::abs(x-y);
}
All the existing answers will overflow on extreme inputs, giving undefined behaviour. #craq pointed this out in a comment.
If you know that your values will fall within a narrow range, it may be fine to do as the other answers suggest, but to handle extreme inputs (i.e. to robustly handle any possible input values), you cannot simply subtract the values then apply the std::abs function. As craq rightly pointed out, the subtraction may overflow, causing undefined behaviour (consider INT_MIN - 1), and the std::abs call may also cause undefined behaviour (consider std::abs(INT_MIN)). It's no better to determine the min and max of the pair and to then perform the subtraction.
More generally, a signed int is unable to represent the maximum difference between two signed int values. The unsigned int type should be used for the output value.
I see 3 solutions. I've used the explicitly-sized integer types from stdint.h here, to close the door on uncertainties like whether long and int are the same size and range.
Solution 1. The low-level way.
// I'm unsure if it matters whether our target platform uses 2's complement,
// due to the way signed-to-unsigned conversions are defined in C and C++:
// > the value is converted by repeatedly adding or subtracting
// > one more than the maximum value that can be represented
// > in the new type until the value is in the range of the new type
uint32_t difference_int32(int32_t i, int32_t j) {
static_assert(
(-(int64_t)INT32_MIN) == (int64_t)INT32_MAX + 1,
"Unexpected numerical limits. This code assumes two's complement."
);
// Map the signed values across to the number-line of uint32_t.
// Preserves the greater-than relation, such that an input of INT32_MIN
// is mapped to 0, and an input of 0 is mapped to near the middle
// of the uint32_t number-line.
// Leverages the wrap-around behaviour of unsigned integer types.
// It would be more intuitive to set the offset to (uint32_t)(-1 * INT32_MIN)
// but that multiplication overflows the signed integer type,
// causing undefined behaviour. We get the right effect subtracting from zero.
const uint32_t offset = (uint32_t)0 - (uint32_t)(INT32_MIN);
const uint32_t i_u = (uint32_t)i + offset;
const uint32_t j_u = (uint32_t)j + offset;
const uint32_t ret = (i_u > j_u) ? (i_u - j_u) : (j_u - i_u);
return ret;
}
I tried a variation on this using bit-twiddling cleverness taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax but modern code-generators seem to generate worse code with this variation. (I've removed the static_assert and the comments.)
uint32_t difference_int32(int32_t i, int32_t j) {
const uint32_t offset = (uint32_t)0 - (uint32_t)(INT32_MIN);
const uint32_t i_u = (uint32_t)i + offset;
const uint32_t j_u = (uint32_t)j + offset;
// Surprisingly it helps code-gen in MSVC 2019 to manually factor-out
// the common subexpression. (Even with optimisation /O2)
const uint32_t t = (i_u ^ j_u) & -(i_u < j_u);
const uint32_t min = j_u ^ t; // min(i_u, j_u)
const uint32_t max = i_u ^ t; // max(i_u, j_u)
const uint32_t ret = max - min;
return ret;
}
Solution 2. The easy way. Avoid overflow by doing the work using a wider signed integer type. This approach can't be used if the input signed integer type is the largest signed integer type available.
uint32_t difference_int32(int32_t i, int32_t j) {
return (uint32_t)std::abs((int64_t)i - (int64_t)j);
}
Solution 3. The laborious way. Use flow-control to work through the different cases. Likely to be less efficient.
uint32_t difference_int32(int32_t i, int32_t j)
{ // This static assert should pass even on 1's complement.
// It's just about impossible that int32_t could ever be capable of representing
// *more* values than can uint32_t.
// Recall that in 2's complement it's the same number, but in 1's complement,
// uint32_t can represent one more value than can int32_t.
static_assert( // Must use int64_t to subtract negative number from INT32_MAX
((int64_t)INT32_MAX - (int64_t)INT32_MIN) <= (int64_t)UINT32_MAX,
"Unexpected numerical limits. Unable to represent greatest possible difference."
);
uint32_t ret;
if (i == j) {
ret = 0;
} else {
if (j > i) { // Swap them so that i > j
const int32_t i_orig = i;
i = j;
j = i_orig;
} // We may now safely assume i > j
uint32_t magnitude_of_greater; // The magnitude, i.e. abs()
bool greater_is_negative; // Zero is of course non-negative
uint32_t magnitude_of_lesser;
bool lesser_is_negative;
if (i >= 0) {
magnitude_of_greater = i;
greater_is_negative = false;
} else { // Here we know 'lesser' is also negative, but we'll keep it simple
// magnitude_of_greater = -i; // DANGEROUS, overflows if i == INT32_MIN.
magnitude_of_greater = (uint32_t)0 - (uint32_t)i;
greater_is_negative = true;
}
if (j >= 0) {
magnitude_of_lesser = j;
lesser_is_negative = false;
} else {
// magnitude_of_lesser = -j; // DANGEROUS, overflows if i == INT32_MIN.
magnitude_of_lesser = (uint32_t)0 - (uint32_t)j;
lesser_is_negative = true;
}
// Finally compute the difference between lesser and greater
if (!greater_is_negative && !lesser_is_negative) {
ret = magnitude_of_greater - magnitude_of_lesser;
} else if (greater_is_negative && lesser_is_negative) {
ret = magnitude_of_lesser - magnitude_of_greater;
} else { // One negative, one non-negative. Difference is sum of the magnitudes.
// This will never overflow.
ret = magnitude_of_lesser + magnitude_of_greater;
}
}
return ret;
}
Well it depends on what you mean by shortest. The fastet runtime, the fastest compilation, the least amount of lines, the least amount of memory. I'll assume you mean runtime.
#include <algorithm> // std::max/min
int diff = std::max(x,y)-std::min(x,y);
This does two comparisons and one operation (this one is unavoidable but could be optimized through certain bitwise operations with specific cases, compiler might actually do this for you though). Also if the compiler is smart enough it could do only one comparison and save the result for the other comparison. E.g if X>Y then you know from the first comparison that Y < X but I'm not sure if compilers take advantage of this.