Tipok
Tipok

Reputation: 695

Bitwise operations with int

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,

  1. 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?

  2. 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

Upvotes: 0

Views: 2917

Answers (2)

Lundin
Lundin

Reputation: 213276

  1. 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.

  2. 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.

Upvotes: 2

Waqas Shabbir
Waqas Shabbir

Reputation: 753

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.

Upvotes: 1

Related Questions