Reason for using bit manipulation in array size [closed] - c++

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 5 years ago.
Improve this question
I have recently got a basic idea of bit manipulation, and I was going through a problem where I found this C++ statement:
int popcount[1<<16];
I do have a basic idea of left/right Bit shift, but I would like to know why it is used in array size place.

Unless you find a comment in the code and unless you find out what the intent of popcount is, one can just guess why one writes 1 << 16 instead of, for example, 65536.
A common case could be that you want to count the number of occurrences of a particular id in, for example, a file. If the range of such an id where 16 bits, then such code could look as follows. The [1<<16] then expresses that you expect a range of not more than 16 bits:
int popcounts[1<<16] = { 0 };
int main() {
uint16_t id;
while (myfile >> id) {
popcounts[id]++;
}
}
Note that this is more accurate than writing int popcounts[UINT_MAX], because UINT_MAX is guaranteed to be equal or greater than 65536, and it is not guaranteed to be exactly 65536.

1<<16 is a common way to write 2 ** 16, which is easier to verify and modify than the "magic number" 65536. You may also encounter things like 1000 * 1000 instead of 1000000 for the same reason (although C++14 allows for 1000'000).

Related

How sizeof(std::cout) is 140 whereas sizeof(std::string) is only 4? [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 7 years ago.
Improve this question
Consider following program:
#include <iostream>
int main()
{
std::cout<<sizeof(std::string)<<'\n';
std::cout<<sizeof(std::ostream)<<'\n';
std::cout<<sizeof(std::istream)<<'\n';
std::cout<<sizeof(std::cout);
}
The output on my compiler(g++ 4.8.1) is
4
140
144
140
The output really confuses me. Why sizeof string class is only 4 bytes & for ostream & istream it gives 140 & 144 bytes respectively? The sizeof(std::cout)is 140 bytes that is same as sizeof(std::ostream). So, I think because cout object is of type ostream that's why I am getting output same here. right? Are these sizes compiler dependent?
Basically it comes down to the fact that an iostream has quite a bit of state to store, but a string has very little.
Nonetheless, the idea of a string having a size of only 4 is a little surprising (at least to me). I'd normally expect something like 12 for a 32-bit implementation, or 24 for a 64-bit version.
In particular, a string will typically contain three things: a pointer to the actual buffer to hold the data (typically allocated on the free store), a size_t to contain the size of that buffer, and a size_t to contain the number of characters currently being stored. In a typical case, each of those will be 32-bits on a 32-bit implementation and 64-bits on a 64-bit implementation.
It's entirely possible to justify a string object that's somewhat larger than that as well--for example, it's fairly common to store the data for a small string directly in the string object itself ("short string optimization"). In this case, you might have space for (up to) something like 20 characters in the string object itself, which will typically increase its size still further.

What is the size of bool? 1 bit or 1 byte? [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 8 years ago.
Improve this question
printf("bool: %zu; true: %zu; 1: %zu\n", sizeof (bool), sizeof true, sizeof 1);
The above piece of code yields
bool: 1; true: 1; 1: 4
I am fine with the sizeof(1), it is an integer and hence 4 bytes size.
But bool (and true) only needs a size of 1 "bit", still the output is 1 i.e. 1 byte.
Why is this so?
For an efficient (packed) representation use std::bitset:
#include <bitset>
std::bitset<2000000> my_bits;
Obviously this is for C++ only. In C you would have to implement this explicitly yourself, e.g.:
#include <stdint.h>
#include <limits.h>
uint8_t my_bits[2000000 / CHAR_BIT];
and then to access individual bits you would need to implement some simple inline functions using bitwise operations.
The minimum addressable unit is byte. Each object shall have its address. Also sizeof operator returns number of bytes occupied by an object. Even empty structures in C++ shall have non-zero sizes.
You can use standard class std::bitset instead of a boolean array.
An alternative to compile sized std::bitset<N> is to use the specialization std::vector<bool> which has a dynamic size. But care, it doesn't act as regular container as it provides proxy to access individual bit.

C++ program for power but without using pow function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm a newbee in C++ and I'm writing a C++ program that asks the user to input two integers and then it raises the first integer to the power specified by the second integer. For example, if the user enters 5 and 8, the result will be 5 subscript 8, i.e., number five will be raised to the eighth power. The program must not use any pre-defined C++ functions (like pow function) for this task. The program should allow the user to perform another calculation if they so desire. Can anyone help
I'm not going to give you any code, because that won't allow you to truly explore this concept. Rather, you should use this pseudo code to implement something on your own.
Create a function which accepts two inputs, the base and the exponent.
Now there are several ways to go about doing this. You can use efficient bit shifting, but let's start simple, shall we?
answer = base
i = 1
while i is less than or equal to exponent
answer = answer * base
return answer
Simply loop through multiplying the base by itself.
There are other ways that focus on efficiency. Look here to see something that you may want to attempt: are 2^n exponent calculations really less efficient than bit-shifts?
The program must not use any pre-defined C++ functions (like pow function) for this task
You can use some piece of c++ code like follows, to compute xy, without using any predefined function:
int x = 5;
int y = 3;
int result = 1;
for(int i = 0; i < y; ++i)
{
result *= x;
}
cout << result << endl;
Output:
125
See a working sample here.

What is the use of bit fields in a struct? [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 9 years ago.
Improve this question
Bit fields in a structure can be used to save some bytes of memory, I have heard. How can we use this particular bytes for any purposes?
typedef struct
{
char A : 1;
int B : 1;
} Struct1;
The char value itself with a width of one bit is not particularly useful. In fact char values as bit fields are not standard. It's an extension that Microsoft added. On the other hand the B field can be used as on / off value since it can hold the values 1 or 0
Struct1 s;
s.B = 0;
if (s.B) {
...
}
This particular example doesn't really demonstrate the savings offered by bit fields particularly well. Need a more complex strut for that. Consider the following
typedef struct {
int Value1;
int Value2;
} S1;
On most platforms S1 will have a size of 8 (each int field being 4 bytes long). Imagine though that Value1 and Value2 will always have values between 0 and 10. This could be stored in 4 bits but we're using 32 bits meaning. Using bit fields we could reduce the waste significantly here
typedef struct {
int Value1 : 4;
int Value2 : 4;
} S1;
Now the size of S1 is likely 1 byte and can still hold all of the necessary values
In embedded systems, the bit fields in a structure can be used to represent bit fields or a hardware device.
Other uses for bit fields are in protocols (messages). One byte (or 4 bytes) to represent the presences or absences of many things would occupy a lot a space and wasted transmission time. So in 1 byte you could represent 8 Boolean conditions rather than using 8 bytes or 8 words to do so.
The bit fields in a structure are usually used as convenience. The same operations to extract, set or test bit fields can be performed using the arithmetic bit operators (such as AND).
Saving memory means, that you need less memory. This can increase the program performance due to less swapping or cache misses.
In your example the two parts A and B would be stored in a byte (or whatever the compiler decides to use), instead of two. A better example is, if you want to store the occupied seats in an opera house with 1000 seats. If you would store them as a boolean which is often stored in a byte per boolean, they could be stored in 128 bytes, because per seat only one bit is needed.
The downside is the performance loss. Accessing the bits need some additional shifting or xor-ing. Thus, it's a trade-off memory for computation time.

Combing 3 byte/pin values into one byte [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 4 pin values defined P1_1, P1_2, P1_3, P1_4, with bit values. (1/0)
I want to combine them into one byte value, example:
0000 0101 (3 LSB are the pins)
How can i do this?
Something like
value = (P1_1<<3)|(P1_2<<2)|(P1_3<<1)|(P1_4);
Disclaimers: this is pretty ugly example. In your actual code you probably want some kind of constants defined for shift (so you are able to do the reverse operation without using more magic literal values).
Also note that this will have unexpected results if one of P constants is not 0 or 1. In this case one might use something like !!P1_x instead of P1_x.
bitset<4> temp;
temp[0] = P1_1;
temp[1] = P1_2;
temp[2] = P1_3;
temp[3] = P1_4;
unsigned char value = static_cast<unsigned char>(temp.to_ulong());