Astudent
Astudent

Reputation: 196

How to edit single bits from an unsigned char

My goal is to write a function which receives an unsigned char as input, and returns a modified unsigned char as an output.

The char should be modified so that its first three bits are set as zeros, and the rest are left untouched. Example function written below.

Any help is greatly appreciated. Apologies for the somewhat incomplete question, this is the most accurate description I can give.

unsigned char Changebits(unsigned char b)
{
    //set the first three bits of the input to zeros (for example 10110111 -> 00010111)
    return //insert the modified unsigned char here
}

Upvotes: 0

Views: 1245

Answers (3)

priojeet priyom
priojeet priyom

Reputation: 908

I am assuming you know about bitwise AND operation.

suppose we have 10110111 as input. to make first three digits 0, we can simply do a bitwise on it with a number with contains 0 in first three positions and have 1 in remaining positions(00011111).

unsigned char Changebits(unsigned char b)
{
    unsigned char modifier = 31; //00011111in binary is equal to 11100000 in decimal
    return b & modifier; // in c '&' represents bitwise AND operation
}

Another cool way to define modifier is:

unsigned char modifier = (1<<5)-1; //using bitwise left shift

Upvotes: 1

Kampi
Kampi

Reputation: 1891

Please read something about bitmanipulation in C. So your solution looks something like this (assuming 1 byte char)

unsigned char Changebits(unsigned char b)
{
    return (b & 0x1Fu);
}

Upvotes: 2

Alexander Mitichev
Alexander Mitichev

Reputation: 11

unsigned char Changebits(unsigned char b)
{
    return b&0x1F;
}

Upvotes: 1

Related Questions