C: Bit operations

Source: Internet
Author: User
Tags binary to decimal bitwise integer

1. Negative numbers-two types of complements (twos complement)

Generally use the two class complement to indicate a negative number, the leftmost one is a sign bit.

When converting a decimal negative to a binary symbol number, you first add 1 to the number, then the absolute value, then convert it to binary, and finally the binary is mended.

[1]-5

[2]-4

[3]4

[4]0000 0100

[5]1111 1011

Converts a negative number from binary to decimal, first to all its bits, and then converts the result to decimal, changing its symbol, and then minus 1.

[1]1111 1011

[2]0000 0100

[3]4

[4]-4

[5]-5

When using a two-class complement to represent a number, the maximum positive number that can be stored with n bits is 2n-1-1, with an n-bit-stored minimum negative -2n-1.

Assuming that the integer occupies 32 bits (4 bytes), the maximum positive number that can be stored is 231-1, the smallest negative number is 231, and an unsigned integer, or unsigned int, has a range of 0 to 232-1.

2. Bitwise-and-bitwise OR

Bitwise and often used to mask certain bits in a number,

Word &= 0x1//except the rightmost 4 digits, the remaining bits are cleared

Bitwise or often used to set certain bits to 1

Word |= 0x1//Sets the rightmost 4-bit to 1

3. Xor or operation

A different or operation can exchange two values without using a temporary variable.

/*exchange two integer values*/
void swap(int * a, int * b)
{
  *a ^= *b;
  *b ^= *a;
  *a ^= *b;
}

If a number and 1 of the difference or operation, can achieve the reverse effect, 0^1=1,1^1=0.

This assumes that the machine has an integer length of 32 bits and a reverse of 31 digits of the integer 0 to get the largest integer.

int main()
{
  int a=0;
  printf("%i,%i",a,a ^ 0x7fffffff);
  return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.