c++: How to flip the binary values of each bit in int - c++

Suppose I have an integer int a
In c++, as this int uses 4 bytes(32 bits) of memory, all bits would be occupied by either 1's or 0's. So, I wish to flip the values of each bit. That is, wherever in each bit there is 1 convert it to 0 and 0 to 1.
Is there an easy way to go about this?
Edit: I also want to play with boolean algebra also. That is if I can execute basic boolean operations like addition, subtraction, etc.

You're looking for the binary not operator (~).
So
int a = 0x04;
int b = ~a;
the value of b is 1111 1111 1111 1011 while the value of a is 0000 0000 0000 0100.
The wikipedia and the GNU C have plenty of information of these binary operators.

Here is an example of bitwise NOT operator:
#include <iostream>
int main()
{
int a = 0;
int x = ~a;
unsigned int y = ~a;
std::cout << x << '\n';
std::cout << y << '\n';
}
Output:
-1
4294967295
For more information about binary operators and more try here

Related

C++ Math Weird After 65536

This is my first question asked so I am not sure exactly what to say. Basically, I wrote a program to find the diagonal of a rectangular prism with the inputs for length, width, and height being whole numbers ranging from 1 - 100,000. (The output of this function would only be stated in the console if it was a whole number.) Everything seems to work until it got to the number 65536, after which, the next output was 0.
I am still new to programming, and if I missed anything, feel free to ask, thank you all in advance!
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include<math.h>
#include <cmath>
int l = 1;
int w = 1;
int h = 1;
double temp1;
double temp2;
double Hypo1;
double temp3;
double Hypo2;
double temp4;
int main(){
while(h < 100000){
//Math to find diagonal of rectangular prism.
temp1 = l * l;
temp2 = w * w;
Hypo1 = temp1 + temp2;
temp3 = h * h;
temp4 = Hypo1 + temp3;
Hypo2 = sqrt(temp4);
//Output if answer is a whole number.
if(abs(floor(Hypo2)) == Hypo2){
std::cout << "<Length = "; std::cout << l;
std::cout << " | Width = "; std::cout << w;
std::cout << " | Height = "; std::cout << h;
std::cout << ">";
std::cout << " Total:"; std::cout << Hypo2 << std::endl;
}
//Add one to each input.
if(l == w && l == h){
l++;
}
else if(w < l && w == h){
w++;
}
else if(h < l && h < w){
h++;
}
}
}
Welcome to the wonders of Overflow.
So, here's what's happening:
You're using int, which stores values in a 4 byte (32 bit) variable. When you multiply two numbers stored in X bits you may need to store the result in 2*X bits.
In this case, 65536 is, in binary, 0000 0000 0000 0001 0000 0000 0000 0000 (in hex, 0x 0001 0000). When you multiply 65536 by itself, the result will be 1 0000 0000 0000 0000 0000 0000 0000 0000 (in hex, 0x 1 0000 0000). Now, the problem is that this value needs 33 bits to be correctly stored. As it only has 32, it stored the 32 least significant bits and discards the most significant bit. As such, the stored value will be 0. This is also what happens with greater values.
To correct this, replace int with long long or, even better, unsigned long long.
As a personal advice, get used to uint32_t and other standard types. They will come in handy. To use these, #include <cstdint>. In this case, you should use uint64_t to store unsigned integers in a 64-bit variable
You declared h as an int, so the result of h*h will also be an int. The conversion to double happens after the calculation is already done.
If you take a look at INT_MAX it's probably 2,147,483,647 on your platform.
So if you look at 65536 * 65536 it's 4,294,967,296, well outside of the value range.
If you convert one of the factors into a double value first, you might have some more luck temp3 = double(h) * h

How to read 8bits RAW data from file

I have 8 bit raw data representing a grayscale image (int value 0-255) in a file looking like this:
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 001c 354d 6576 8797
9fa4 a7a4 864b 252e 5973 7673 7b86 7e6d
6164 6c7a 8b98 a2ac b8bd ae96 857f 6d40
1d14 160b 0000 0000 0000 0000 0000 0000
and i need to read them and print their int value (0-255).
I try this, but all result looks like this: 0020 0a00 2000 2000 2000 2000 2000 2000
I dont know what is wrong, fopen as binary file is OK?
FILE * pFile;
pFile = fopen(inFileName.c_str(), "rb");
if (pFile==NULL){
cerr << "erro" << endl;
}
uint8_t bufferImmagine[height*width];
fread(bufferImmagine,1,height*width,pFile);
fclose (pFile);
for (int i = 0; i < height*width; ++i)
{
cout << bufferImmagine[i] << " ";
}
So bufferImmagine is an array of type uint8_t, and on many platforms uint8_t is an alias for unsigned char. When you stream unsigned char into std::cout, the stream treats it like a character, rather than a number.
If you want to print out each byte as a number 0-255, convert each byte to a wider integral type, like unsigned:
std::cout << static_cast<unsigned int>(bufferImmagine[i]) << " ";
I see a few potential problems with the code:
1) As mentioned in the comments, uint8_t bufferImmagine[height*width]; is problematic, in that C++ doesn't support variable-length arrays, so unless height and width can be made into compile-time constants, it would be better to use a std::vector instead (or if you are allergic to data structures you could allocate an array with the new operator, but then you risk leaking memory if you aren't very careful).
2) Depending on the values of width and height, the size of bufferImmagine could be quite large; possibly larger than the amount of stack space available. Another reason to use std::vector or allocate on the heap, instead.
3) You never check the return value of the fread() call to see if it read all of the data, or not. It might be reading fewer bytes than you asked it to read (most likely because the file you're reading isn't long enough), but without checking the value you won't know anything has gone wrong, so you'll be very confused if/when an error occurs.
4) As Jack C. mentioned in his answer, cout may print out uint8_t's as ASCII characters rather than integers, which isn't what you want here.
5) Not really a problem, but if you'd like the rows of your output to correspond to the rows-of-pixels in your file, then you'll want to apply carriage returns at the end of each 'row'. E.g.:
int i = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
const unsigned int iVal = bufferImmagine[i];
cout << iVal << " ";
i++;
}
cout << endl;
}

C++ bitwise complement in unsigned integer returns negative values

I am just trying to do the bitwise complement in C++ with ~ operator:
For example:
NOT 0101
--------
1010
So in the following code, I was expecting to get 1010 but I am getting negative numbers. How is it possible although I define the values with unsigned types?
#include <iostream>
#include <stdio.h>
#include <string>
#include <bitset>
using namespace std;
int tob(int num) {
if (num == 0)
return 0;
return (num % 2) + 10*tob(num/2);
}
long unsigned int tol(string st) {
long unsigned int num = bitset<100>(st).to_ulong();
return num;
}
int main()
{
unsigned int x = tol("0101");
unsigned int z = ~x;
printf("%10d (decimal %u)\n", tob(z), z);
// -110 (decimal -6)
cout << tob(z) << endl; // -110
cout << z << endl; // -110
}
And how do I get 1010 from not 0101 in C++?
Thanks!
unsigned int has normally 32 bits and all of them are being inverted here:
NOT 0000 0000 0000 0000 0000 0000 0000 0101
-------------------------------------------
1111 1111 1111 1111 1111 1111 1111 1010
If you want only last 4 bits and zero out the rest, apply a mask:
unsigned int z = ~x & 0xf; // 1111 in binary
You can get desired result with simple bitwise XOR too:
unsigned int z = x ^ 0xf;
By the way, your code will fail to print binary representations of larger numbers because int won't be capable of holding values above 2^32 (starting with 100 0000 0000 (decimal)). For that, I recommend printing with std::bitset or the direct approach in the answer below instead of using tob function.
[…] how do I get 1010 from not 0101 in C++?
Use a std::bitset for four bits.
std::bitset<4> x("0101");
auto z = ~x;
std::cout << '~' << x << '=' << z << std::endl;
Example on Coliru

retrieve last 6 bits from an integer

I need to fetch last 6 bits of a integer or Uint32. For example if I have a value of 183, I need last six bits which will be 110 111 ie 55.
I have written a small piece of code, but it's not behaving as expected. Could you guys please point out where I am making a mistake?
int compress8bitTolessBit( int value_to_compress, int no_of_bits_to_compress )
{
int ret = 0;
while(no_of_bits_to_compress--)
{
std::cout << " the value of bits "<< no_of_bits_to_compress << std::endl;
ret >>= 1;
ret |= ( value_to_compress%2 );
value_to_compress /= 2;
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
int val = compress8bitTolessBit( 183, 5 );
std::cout <<" the value is "<< val << std::endl;
system("pause>nul");
return 0;
}
You have entered the realm of binary arithmetic. C++ has built-in operators for this kind of thing. The act of "getting certain bits" of an integer is done with an "AND" binary operator.
0101 0101
AND 0000 1111
---------
0000 0101
In C++ this is:
int n = 0x55 & 0xF;
// n = 0x5
So to get the right-most 6 bits,
int n = original_value & 0x3F;
And to get the right-most N bits,
int n = original_value & ((1 << N) - 1);
Here is more information on
Binary arithmetic operators in C++
Binary operators in general
I don't get the problem, can't you just use bitwise operators? Eg
u32 trimmed = value & 0x3F;
This will keep just the 6 least significant bits by using the bitwise AND operator.
tl;dr:
int val = x & 0x3F;
int value = input & ((1 << (no_of_bits_to_compress + 1) - 1)
This one calculates the (n+1)th power of two: 1 << (no_of_bits_to_compress + 1) and subtracts 1 to get a mask with all n bits set.
The last k bits of an integer A.
1. A % (1<<k); // simply A % 2^k
2. A - ((A>>k)<<k);
The first method uses the fact that the last k bits is what is trimmed after doing k right shits(divide by 2^k).

Assigning max value of smaller integer to a larger integer

Consider the following code:
uint32_t x = ~uint8_t(0);
std::cout << x << std::endl;
Now, I fully expected this to output 255, but instead it output 4294967295.
I'm aware of integer promotion in C++, but I can't understand why this would happen. The way I understand it, the expression ~uint8_t(0) should evaluate to 1111 1111 in binary. The ~ operator will then cause the type to be promoted to an int (which I'll assume is 32-bit for the sake of discussion), by sign extending the value to 0000 0000 0000 0000 0000 0000 1111 1111. This promoted value should then be assigned to the lvalue x, resulting in x == 255.
But obviously I'm not understanding this correctly. What am I missing?
The integral promotions are performed on the operand of the unary ~, so the uint8_t(0) is promoted to int and then the ~ is evaluated. It's equivalent to
~(int)(uint8_t)0
You can get the maximum value representable by a type using std::numeric_limits<T>::max(); if the type is unsigned, you can also cast -1 to that type:
uint32_t x = (uint8_t)-1;
In your example, the bitwise not operator (~) is promoting its operand to an int before it executes. This is then converted to an unsigned int by the assignment.
Here are some related code samples that make this more clear:
uint8_t y = ~uint8_t(0);
uint32_t x = y;
std::cout << x << std::endl;
255
uint8_t y = uint8_t(0);
int z = ~y;
uint32_t x = z;
std::cout << x << std::endl;
4294967295