0

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

2
  • 3
    2. if (n & (1<<6)) { /* bit 6 is 1*/ } Commented Jan 29, 2015 at 10:47
  • 1
    You don't need to convert to binary, there are bitwise operators that let you work directly on the integer. Also note that perhaps you should not depend on the fact that int == 4 bytes, this is not guaranteed by the standard. Commented Jan 29, 2015 at 10:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.