how to store the bit string in array? - c++

how to count number of occurrences of 1 in a 8 bit string. such as 10110001.
bit string is taken from user. like 10110001
what type of array should be used to store this bit string in c?

Short and simple. Use std::bitset(C++)
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> mybitstring;
std::cin >> mybitstring;
std::cout << mybitstring.count(); // returns the number of set bits
}
Online Test at Ideone

Don't use an array at all, use a std::string. This gives you the possibility of better error handling. You can write code like:
bitset <8> b;
if ( cin >> b ) {
cout << b << endl;
}
else {
cout << "error" << endl;
}
but there is no way of finding out which character caused the error.

You'd probably use an unsigned int to store those bits in C.
If you're using GCC then you can use __builtin_popcount to count the one bits:
Built-in Function: int __builtin_popcount (unsigned int x)
Returns the number of 1-bits in x.
This should resolve to a single instruction on CPUs that support it too.

From hacker's delight:
For machines that don't have this instruction, a good way to count the number
of 1-bits is to first set each 2-bit field equal to the sum of the two single
bits that were originally in the field, and then sum adjacent 2-bit fields,
putting the results in each 4-bit field, and so on.
so, if x is an integer:
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF);
x will now contain the number of 1 bits. Just adapt the algorithm with 8 bit values.

Related

Count Total number of set bits for 2 given numbers

Question is Given - To Count Total number of set bits for 2 given numbers . For example take 2 and 3 as input . So 2 represents - 10 in binary form and 3 represents - 11 in binary form , So total number of set bits = 3.
My work -
#include <iostream>
using namespace std;
int bit(int n1, int n2){
int count = 0;
while(n1 != 0 && n2 != 0){
if(n1 & 1 || n2 & 1) {
count++;
}
n1 >> 1;
n2 >> 1;
}
return count;
}
int main() {
int a;
cin >> a;
int b;
cin >> b;
cout << bit(a,b);
return 0;
}
Expected Output - 3
So please anyone knows what i am doing wrong please correct it and answer it.
Why ask the question for 2 numbers if the intended combined result is just the sum of the separate results?
If you can use C++20, std::popcount gives you the number of set bits in one unsigned variable.
If you can't use C++20, there is std::bitset. Construct one from your number and use its method count.
So your code becomes:
int bit(int n1, int n2) {
#if defined(__cpp_lib_bitops)
return std::popcount(static_cast<unsigned int>(n1)) + std::popcount(static_cast<unsigned int>(n2));
#else
return std::bitset<sizeof(n1)*8>(n1).count() + std::bitset<sizeof(n2)*8>(n2).count();
#endif
}
Demo
I'm not quite sure what happens if you give negative integers as input. I would do a check beforehand or just work with unsigned types from the beginning.
What you are doing wrong was shown in a (now deleted) answer by Ankit Kumar:
if(n1&1 || n2&1){
count++;
}
If a bit is set in both n1 and n2, you are including it only once, not twice.
What should you do, other than using C++20's std::popcount, is to write an algorithm1 that calculates the number of bits set in a number and then call it twice.
Also note that you should use an unsigned type, to avoid implementation defined behavior of right shifting a (possibly) signed value.
1) I suppose that is the purpose of OP's exercise, everybody else shuold just use std::popcount.
It is possible without a loop, no if and only 1 variable.
First OR the values together
int value = n1 | n2; // get the combinedd bits
Then divide value in bitblocks
value = (value & 0x55555555) + ((value >> 1) & 0x55555555);
value = (value & 0x33333333) + ((value >> 1) & 0x33333333);
value = (value & 0x0f0f0f0f) + ((value >> 1) & 0x0f0f0f0f);
value = (value & 0x00ff00ff) + ((value >> 1) & 0x00ff00ff);
value = (value & 0x0000ffff) + ((value >> 1) & 0x0000ffff);
This works for 32bit values only, adjust fopr 64bit accordingly

Given an unsigned integer, it's easy to swap every even and odd bit. Can this be generalized to swapping every even and odd n bits?

In the case where n = 1, if we have an unsigned 32bit integer i, the swapped integer would be
((i & 0xaaaaaaaa) >> 1) | ((i & 0x55555555) << 1)
When n = 2
((i & 0xcccccccc) >> 2) | ((i & 0x33333333) << 2)
When n = 4
((i & 0xf0f0f0f0) >> 4) | ((i & 0x0f0f0f0f) << 4)
and so on.
What about if n is an arbitrary power of 2? ...and, let's say that i is an arbitrary 128bit integer rather than a 32bit integer so we have 7 cases rather than 5?
I suspect there is a way to generalize the process for a given n (i.e. generating that mask from n), and it would be nice to have that so that I don't necessarily have to hardcode each individual case whenever it comes up (for example, implementing certain Cryptographic Hash Functions--e.g. JH).
The obvious method that comes to mind is to loop through the potential mask, with fewer iterations in the case where n is larger but I'd rather have a method that would complete in constant time with fewer operations.
Something that should work for a 32bit integer, for instance:
uint32_t mask = 0; submask = (2n) - 1;
for (uint32_t index = 0; index < 32; index += 2n)
{
mask |= submask;
submask <<= 2n;
}
Is there a better way to generate that mask (ideally without the loop)?
edit: Just occurred to me that instead of
((i & 0xaaaaaaaa) >> 1) | ((i & 0x55555555) << 1)
you could do
((i & 0xaaaaaaaa) >> 1) | ((i << 1) & 0xaaaaaaaa)
which would allow wouldn't require the use of the inverted mask at all. On the off chance someone were to view this for reference, that might be convenient.
This method is somewhat more efficient I think. You can either store or generate the first mask value. Forgive me if my c++ isn't quite right, I'm more of a php/javascript programmer. This code will generate all the masks in turn, so you could save them into an array or just stop the loop at the mask you wanted:
uint32_t mask = 0xffffffff; // can perhaps use int32 and -1?
for (uint32_t i = 4; i >= 0; i--) {
mask ^= mask >> (1 << i);
cout << mask;
}

Swapping lower byte (0-7) with the higher one (8-15) one

I now know how it's done in one line, altough I fail to realise why my first draft doesn't work aswell. What I'm trying to do is saving the lower part into a different variable, shifting the higher byte to the right and adding the two numbers via OR. However, it just cuts the lower half of the hexadecimal and returns the rest.
short int method(short int number) {
short int a = 0;
for (int x = 8; x < 16; x++){
if ((number & (1 << x)) == 1){
a = a | (1<<x);
}
}
number = number >> 8;
short int solution = number | a;
return solution;
You are doing it one bit at a time; a better approach would do it with a single operation:
uint16_t method(uint16_t number) {
return (number << 8) | (number >> 8);
}
The code above specifies 16-bit unsigned type explicitly, thus avoiding issues related to sign extension. You need to include <stdint.h> (or <cstdint> in C++) in order for this to compile.
if ((number & (1 << x)) == 1)
This is only going to return true if x is 0. Since 1 in binary is 00000000 00000001, and 1 << x is going to set all but the x'th bit to 0.
You don't care if it's 1 or not, you just care if it's non-zero. Use
if (number & (1 << x))

How to split an unsigned long int (32 bit) into 8 nibbles?

I am sorry if my question is confusing but here is the example of what I want to do,
lets say I have an unsigned long int = 1265985549
in binary I can write this as 01001011011101010110100000001101
now I want to split this binary 32 bit number into 4 bits like this and work separately on those 4 bits
0100 1011 0111 0101 0110 1000 0000 1101
any help would be appreciated.
You can get a 4-bit nibble at position k using bit operations, like this:
uint32_t nibble(uint32_t val, int k) {
return (val >> (4*k)) & 0x0F;
}
Now you can get the individual nibbles in a loop, like this:
uint32_t val = 1265985549;
for (int k = 0; k != 8 ; k++) {
uint32_t n = nibble(val, k);
cout << n << endl;
}
Demo on ideone.
short nibble0 = (i >> 0) & 15;
short nibble1 = (i >> 4) & 15;
short nibble2 = (i >> 8) & 15;
short nibble3 = (i >> 12) & 15;
etc
Based on the comment explaining the actual use for this, here's an other way to count how many nibbles have an odd parity: (not tested)
; compute parities of nibbles
x ^= x >> 2;
x ^= x >> 1;
x &= 0x11111111;
; add the parities
x = (x + (x >> 4)) & 0x0F0F0F0F;
int count = x * 0x01010101 >> 24;
The first part is just a regular "xor all the bits" type of parity calculation (where "all bits" refers to all the bits in a nibble, not in the entire integer), the second part is based on this bitcount algorithm, skipping some steps that are unnecessary because certain bits are always zero and so don't have to be added.

How to get the most significant non-zero byte in a 32 bit integer without a while loop?

I have a method to extract the most significant, non-zero byte in an integer using the following method:
private static int getFirstByte(int n)
{
while (n > 0xFF)
n >>= 8;
return n;
}
There's a logic problem with this method. The integer parameter could be negative, which means it would return the number being passed in, which is incorrect.
There is also a possible issue with the method itself. It is using a while loop.
Is there a way to perform this logic without a while loop and also possibly avoiding the incorrectly returned result for negative numbers?
Not clever, not elegant - but I believe it does "extract the most significant, non-zero byte in an integer ... without using a loop":
private static int getFirstByte(int n) {
int i;
if ((i = n & 0xff000000) != 0)
return (i >> 24) & 0xff;
if ((i = n & 0xff0000) != 0)
return (i >> 16) & 0xff;
if ((i = n & 0xff00) != 0)
return (i >> 8) & 0xff;
// all of the higher bytes are zeroes
return n;
}
You could use log n / log 256… But then you’d have a bigger problem.
I assume by get the first non-zero byte in an int you mean natural 8 bit breaks of the int and not a dynamic 8 bit break.
Natural 8 bit breaks:
00000000|00010110|10110010|11110001 ==> 00010110
Dynamic 8 bit break:
00000000000|10110101|1001011110001 ==> 10110101
This will return the first non-zero byte on a natural 8-bit break of an int without looping or branching. This code may or may not be more efficient then paulsm4's answer. Be sure to do benchmarking and/or profiling of the code to determine which is best for you.
Java Code: ideone link
class Main {
public static void main(String[] args) {
int i,j;
for (i=0,j=1; i<32; ++i,j<<=1) {
System.out.printf("0x%08x : 0x%02x\n",j,getByte(j));
}
}
public static byte getByte(int n) {
int x = n;
x |= (x >>> 1);
x |= (x >>> 2);
x |= (x >>> 4);
x |= (x >>> 8);
x |= (x >>> 16);
x -= ((x >>> 1) & 0x55555555);
x = (((x >>> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >>> 4) + x) & 0x0f0f0f0f);
x += (x >>> 8);
x += (x >>> 16);
x &= 0x0000003f;
x = 32 - x; // x now equals the number of leading zeros
x &= 0x00000038; // mask out last 3 bits (cause natural byte break)
return (byte)((n&(0xFF000000>>>x))>>>(24-x));
}
}