Excuse me for my english. I have a number of int values stored in it from 0 to 255. To find out what lies in 7 bit number, I translate the numbers into a binary system, then in the line and check the line:
if (informationOctet_.substr(6, 1) == "0")
{
...
}
Two questions arose,
If I use int (which we have 4 bytes), and my number is unsigned int the range [0, 255] How do I determine which byte I need to consider? High byte?
I have found the desired byte, how do you know the contents of, for example, the 6th bit?
P.S.
I do not use spells, because do with unsigned int.
THANK ALL, I test int number:
int k = 3;
for (int i = 0; i < 8; i++)
{
if (k & (1 << i))
{
std::cout << 1;
}
else
{
std::cout << 0;
}
}
print: 11000000
This is implementation-defined and depends on the endianess of the CPU. If you are smart though, you do the check like this: the_int & 0xFF, which will always give you the least significant byte no matter endianess.
byte & (1 << 6). Maybe. Note that bit counting is zero-indexed (just like arrays), so you have to be careful with the terms. "Bit 6" and "the 6th bit" may have different meanings. Always enumerate bits as 7 6 5 4 3 2 1 0, then it will be consistent with the C code.
You can choose the "Char" Data Type to check. It answer your both question. Because, the character Data Type is of 1 byte (8 bits). And it contains integer values as well because char & int are the compatible data types.
Related
I have an 18 bit integer that is in two's complement and I'd like to convert it to a signed number so I can better use it. On the platform I'm using, ints are 4 bytes (i.e. 32 bits). Based on this post:
Convert Raw 14 bit Two's Complement to Signed 16 bit Integer
I tried the following to convert the number:
using SomeType = uint64_t;
SomeType largeNum = 0x32020e6ed2006400;
int twosCompNum = (largeNum & 0x3FFFF);
int regularNum = (int) ((twosCompNum << 14) / 8192);
I shifted the number left 14 places to get the sign bit as the most significant bit and then divided by 8192 (in binary, it's 1 followed by 13 zeroes) to restore the magnitude (as mentioned in the post above). However, this doesn't seem to work for me. As an example, inputting 249344 gives me -25600, which prima facie doesn't seem correct. What am I doing wrong?
The almost-portable way (with assumption that negative integers are natively 2s-complement) is to simply inspect bit 17, and use that to conditionally mask in the sign bits:
constexpr SomeType sign_bits = ~SomeType{} << 18;
int regularNum = twosCompNum & 1<<17 ? twosCompNum | sign_bits : twosCompNum;
Note that this doesn't depend on the size of your int type.
The constant 8192 is wrong, it should be 16384 = (1<<14).
int regularNum = (twosCompNum << 14) / (1<<14);
With this, the answer is correct, -12800.
It is correct, because the input (unsigned) number is 249344 (0x3CE00). It has its highest bit set, so it is a negative number. We can calculate its signed value by subtracting "max unsigned value+1" from it: 0x3CE00-0x40000=-12800.
Note, that if you are on a platform, for which right signed shift does the right thing (like on x86), then you can avoid division:
int regularNum = (twosCompNum << 14) >> 14;
This version can be slightly faster (but has implementation-defined behavior), if the compiler doesn't notice that division can be exactly replaced by a shift (clang 7 notices, but gcc 8 doesn't).
Two problems: first your test input is not an 18-bit two's complement number. With n bits, two's compliment permits -(2 ^ (n - 1)) <= value < 2 ^ (n - 1). In the case of 18 bits, that's -131072 <= value < 131071. You say you input 249344 which is outside of this range and would actually be interpreted as -12800.
The second problem is that your powers of two are off. In the answer you cite, the solution offered is of the form
mBitOutput = (mBitCast)(nBitInput << (m - n)) / (1 << (m - n));
For your particular problem, you desire
int output = (nBitInput << (32 - 18)) / (1 << (32 - 18));
// or equivalent
int output = (nBitInput << 14) / 16384;
Try this out.
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 4 years ago.
Improve this question
How would I create a function template which returns the low portion of a number of N bits?
For example, for an 8 bit number, get the least significant 4 bits, for a 16 bit number, get the least significant 8 bits.
To get the lower half of a built-in integer type you can try something like this:
#include <iostream>
#include <climits>
using std::cout;
using std::endl;
template<typename T>
constexpr T lowbits(T v) {
return v & (T(1) << CHAR_BIT * sizeof v / 2) - 1;
}
int main() {
cout << std::hex << (int)lowbits<int8_t>(0xde) << endl; // will print e
cout << std::hex << lowbits<int16_t>(0xdead) << endl; // will print ad
cout << std::hex << lowbits<int32_t>(0xdeadbeef) << endl; // will print beef
cout << std::hex << lowbits<int64_t>(0xbeefdeaddeadbeef) << endl; // will print deadbeef
}
Note that
return v & (T(1) << CHAR_BIT * sizeof v / 2) - 1;
is equivalent to:
return v & (
(static_cast<T>(1)
<<
(CHAR_BIT * (sizeof v) / 2)) // number of bits divided by 2
- 1
);
In essence you are creating a bit-mask (simply another integer) that has 0-bits for all higher bits and 1-bits for all lower bits.
If an integer type has N bits this is done by shifting a 1-bit into the Nth position and then subtracting 1 from it. The subtraction has the result that all bits below the 1 will be set.
And-ing this with the given value yields only the lower half of the value v.
You can easily generalize this approach to retrieving any number of lower bits by replacing CHAR_BIT * sizeof v/2 with the number of bits you want to retrieve.
To get only the higher bits you can simply negate the resulting mask using the ~ operator.
If you require arbitrary sized integers you can try finding the equivalent operations for this procedure in the GNU gmp library.
Let us define a variable called mask which is the pattern to mask off (or retain) some bits. The operation to get the least significant bits is:
result = value & mask;
For an example, test with value == 13 and mask == 7.
This works will all POD types, except for floating point. The least significant Q bits of a floating point, doesn't make sense (unless you really need to do this).
If you have no need for more bits than the largest internal integral type, you could use something like this:
template <typename T>
T low_bits(T data, size_t bit_count)
{
T mask = (1U << bit_count) - 1U;
return value & mask;
}
For a non-template solution, one could use a macro:
#define LOW_BITS(value, bit_count) \
(value & ((1U << bit_count) - 1U))
This lets the compiler figure out the code based on the data type of value.
A macro form of the expression: value & mask.
The thorn or issue comes into play when N > sizeof(*largest type*). In this case, the number can't be represented by internal data types, so one has to come up with a different solution.
The solution for N-bit depends on whether the multi-byte representation of the number is Big Endian or Little Endian. For Big Endian platforms, the least significant value will be at highest address, while on Little Endian platforms, the least significant is at the lowest address.
The solution I'm proposing treats the N-bit number as an array of bytes. A byte contains 8-bits (on most platforms), and bytes can be masked differently than multibyte quantities.
Here's the algorithm:
1. Copy the least significant bytes that are completely masked to the result variable.
2. Mask the next largest byte and copy result byte to result number.
3. Pad remaining bytes with 0.
As far as the function parameters go, you'll need:
1) Pointer to the memory location of the original number.
2) Pointer to the result number.
3) Pointer to the mask.
4) Size of the number, in bytes.
The algorithm can handle N-bit numbers, limited by the amount of memory on the platform.
Note: sorry about not providing code, but I need to get back to work. :-(
I have the question of the title, but If not, how could I get away with using only 4 bits to represent an integer?
EDIT really my question is how. I am aware that there are 1 byte data structures in a language like c, but how could I use something like a char to store two integers?
In C or C++ you can use a struct to allocate the required number of bits to a variable as given below:
#include <stdio.h>
struct packed {
unsigned char a:4, b:4;
};
int main() {
struct packed p;
p.a = 10;
p.b = 20;
printf("p.a %d p.b %d size %ld\n", p.a, p.b, sizeof(struct packed));
return 0;
}
The output is p.a 10 p.b 4 size 1, showing that p takes only 1 byte to store, and that numbers with more than 4 bits (larger than 15) get truncated, so 20 (0x14) becomes 4. This is simpler to use than the manual bitshifting and masking used in the other answer, but it is probably not any faster.
You can store two 4-bit numbers in one byte (call it b which is an unsigned char).
Using hex is easy to see that: in b=0xAE the two numbers are A and E.
Use a mask to isolate them:
a = (b & 0xF0) >> 4
and
e = b & 0x0F
You can easily define functions to set/get both numbers in the proper portion of the byte.
Note: if the 4-bit numbers need to have a sign, things can become a tad more complicated since the sign must be extended correctly when packing/unpacking.
I have a vector which contains a lot of bools. When I get to 1 in the vector, I start reading the next 8 values as bits - and I want to modify a char according to those 8 values.
Example:
I have a char c = 0; (00000000).
My 8 bits according to the vector are (10101010).
How do I go around assigning these values into the bits of a char? Can I use the vector as a mask? If so, how?
Use the bit shift operator <<. It shifts bits by a certain amount.
For example, 5 << 2 is 20, because 101 shifted left by two is 10100, or twenty.
vector<bool> v; // plus initialization
char c;
for(size_t i = 0; i < v.size(); i++) {
c += v[i] << (v.size() - i - 1);
}
This assumes you want this big endian (most signitficant bit first). If you want little endian, change (v.size() - i - 1) to i.
sorry for the stupid question, but how would I go about figuring out, mathematically or using c++, how many bytes it would take to store an integer.
If you mean from an information theory point of view, then the easy answer is:
log(number) / log(2)
(It doesn't matter if those are natural, binary, or common logarithms, because of the division by log(2), which calculates the logarithm with base 2.)
This reports the number of bits necessary to store your number.
If you're interested in how much memory is required for the efficient or usual encoding of your number in a specific language or environment, you'll need to do some research. :)
The typical C and C++ ranges for integers are:
char 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
If you're interested in arbitrary-sized integers, special libraries are available, and every library will have its own internal storage mechanism, but they'll typically store numbers via 4- or 8- byte chunks up to the size of the number.
You could find the first power of 2 that's larger than your number, and divide that power by 8, then round the number up to the nearest integer. So for 1000, the power of 2 is 1024 or 2^10; divide 10 by 8 to get 1.25, and round up to 2. You need two bytes to hold 1000!
If you mean "how large is an int" then sizeof(int) is the answer.
If you mean "how small a type can I use to store values of this magnitude" then that's a bit more complex. If you already have the value in integer form, then presumably it fits in 4, 3, 2, or 1 bytes. For unsigned values, if it's 16777216 or over you need 4 bytes, 65536-16777216 requires 3 bytes, 256-65535 needs 2, and 0-255 fits in 1 byte. The formula for this comes from the fact that each byte can hold 8 bits, and each bit holds 2 digits, so 1 byte holds 2^8 values, ie. 256 (but starting at 0, so 0-255). 2 bytes therefore holds 2^16 values, ie. 65536, and so on.
You can generalise that beyond the normal 4 bytes used for a typical int if you like. If you need to accommodate signed integers as well as unsigned, bear in mind that 1 bit is effectively used to store whether it is positive or negative, so the magnitude is 1 power of 2 less.
You can calculate the number of bits you need iteratively from an integer by dividing it by two and discarding the remainder. Each division you can make and still have a non-zero value means you have one more bit of data in use - and every 8 bits you're using means 1 byte.
A quick way of calculating this is to use the shift right function and compare the result against zero.
int value = 23534; // or whatever
int bits = 0;
while (value)
{
value >> 1;
++bits;
}
std::cout << "Bits used = " << bits << std::endl;
std::cout << "Bytes used = " << (bits / 8) + 1 << std::endl;
This is basically the same question as "how many binary digits would it take to store a number x?" All you need is the logarithm.
A n-bit integer can store numbers up to 2n-1. So, given a number x, ceil(log2 x) gets you the number of digits you need.
It's exactly the same thing as figuring out how many decimal digits you need to write a number by hand. For example, log10 123456 = 5.09151220... , so ceil( log10(123456) ) = 6, six digits.
Since nobody put up the simplest code that works yet, I mind as well do it:
unsigned int get_number_of_bytes_needed(unsigned int N) {
unsigned int bytes = 0;
while(N) {
N >>= 8;
++bytes;
};
return bytes;
};
assuming sizeof(long int) = 4.
int nbytes( long int x )
{
unsigned long int n = (unsigned long int) x;
if (n <= 0xFFFF)
{
if (n <= 0xFF) return 1;
else return 2;
}
else
{
if (n <= 0xFFFFFF) return 3;
else return 4;
}
}
The shortest code way to do this is as follows:
int bytes = (int)Math.Log(num, 256) + 1;
The code is small enough to be inlined, which helps offset the "slow" FP code. Also, there are no branches, which can be expensive.
Try this code:
// works for num >= 0
int numberOfBytesForNumber(int num) {
if (num < 0)
return 0;
else if (num == 0)
return 1;
else if (num > 0) {
int n = 0;
while (num != 0) {
num >>= 8;
n++;
}
return n;
}
}
/**
* assumes i is non-negative.
* note that this returns 0 for 0, when perhaps it should be special cased?
*/
int numberOfBytesForNumber(int i) {
int bytes = 0;
int div = 1;
while(i / div) {
bytes++;
div *= 256;
}
if(i % 8 == 0) return bytes;
return bytes + 1;
}
This code runs at 447 million tests / sec on my laptop where i = 1 to 1E9. i is a signed int:
n = (i > 0xffffff || i < 0) ? 4 : (i < 0xffff) ? (i < 0xff) ? 1 : 2 : 3;
Python example: no logs or exponents, just bit shift.
Note: 0 counts as 0 bits and only positive ints are valid.
def bits(num):
"""Return the number of bits required to hold a int value."""
if not isinstance(num, int):
raise TypeError("Argument must be of type int.")
if num < 0:
raise ValueError("Argument cannot be less than 0.")
for i in count(start=0):
if num == 0:
return i
num = num >> 1