C language Setbits,invert

Source: Internet
Author: User

K&r Exercise 2-6,setbits (x,p,n,y), set the n bits from the p bit in x to the rightmost n-bit value in Y, and the rest of the x remain unchanged.

#include <stdio.h>unsigned setbits (unsigned x, int p, int n,unsigned y) {    int mask;    int pos=p+1-n;    mask=~ (~0<<n) << pos;    X=x & ~mask;    Y=y<<pos & mask;    X=x|y;        return x;} Main () {    int x=012;    int y=077;    printf ("%o\n", Setbits (X,4,3,y));}



All the bits of the ~0 are 1, by the displacement of 0, to establish a shield code, in-place operation is very common

2-7,invert (X,p,n)

#include <stdio.h>unsigned invert (unsigned x, int p, int n) {    return x^ (~ (~0<<n) << (P+1-n));} int main () {    unsigned a=034;    printf ("%o\n", Invert (a,4,3));}



With 1 bitwise XOR, in-situ inversion; with 0 xor, in situ unchanged

C language Setbits,invert

Related Article

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.