Isolating Bits With Bitwise AND in C [duplicate] - c

This question already has answers here:
Understanding the bitwise AND Operator
(4 answers)
Closed 4 years ago.
I'm new to programming and have a question I was hoping I could get some help with.
I have a binary value 0100 0001 0000 0001 which has been assigned to a variable name valhex. I'm supposed to use the bitwise AND operator to make bits 13 through 3 KEEP their current value and ALL other bits are set to zero, then store the result back into the variable valhex. I'm supposed to do this using only one line of C code.
So far all I have is this:
unsigned int valhex = valhex&0000000100000000;
I know this isn't right but this is as far as I can get. I don't know where to put the & symbol in relation to the variable and the binary. I'm also not sure if I'm doing the right thing by making bits 0,1,2,14,15 zeroes. I thank you in advance for any help you might be able to give me.

In bitwise AND (if you recall your truth tables), bits that are ANDed with 1 keep their value, bits that are ANDed with a 0, are set to 0. So if you want to keep bits 13-3, your mask needs to have 1s in position 13-3, and 0s in position 2-0. Also note that to specify a binary literal, you need to prefix it with 0b. Also note that you can not declare and use the variable on the same line because it's uninitialized. The end result is this:
unsigned int valhex = 12345; /* some value */
valhex = valhex & 0x3ff8; /* 0x3ff8 = 0b11111111111000 */
Note that unsigned int is longer than 14 bits and you didn't specify what is supposed to happen to bits in position 14 and up. In this case, they'll be set to 0s as well.

Related

How do you understand the below bit wise operations? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am writing a c program which has bit masking in it. What does the macros below define??
What all these operations <<, >>, | and & do??
1. #define SINE_PHASEREG_BASE (0x3 << 14)
2. #define IOPORT_MODE_MUX_MASK (0x7 << 0) /*!< MUX bits mask */
3. #define IOPORT_MODE_MUX_D ( 3 << 0) /*!< MUX function D */
These are C macros that perform bit shift operations.
Numbers and hardware registers are represented by bits at the lowest level.
Some C basics:
Macros are like functions, but instead of calling the function, the
C preprocessor replacing the text which calls the macro, with the
macro itself.
For example, I can create a simple C macro to add 1 to a number as follows:
#define ADD_ONE(x) ((x)+1)
And then I can compute the value of a number plus one as follows:
int I = ADD_ONE(5);
This will get replaced by the CPP preprocessor as:
int I = ((5)+1);
Then the compiler compiles this into the equivalent of:
int I = 6;
Notice that this "call" to ADD_ONE is done at compile time, not run time since ADD_ONE is a macro, and not a function.
Lines 1 to 3 are C macros, and they replace the text where they are called, prior to the code being compiled. Sometimes this is awesome, and sometimes it does things you don't expect. If you stick to the basics, they can be very useful, but experts can make code dance with these things.
Numbers are represented by binary numbers, with the rightmost bit
(the least significant bit aka b0) representing the value 0 if the
bit is zero, or 1 if it is a one, or b0*(2^0).
Why the complicated way of expressing zero or one? Because, the other bits use the similar formula. Bit 1 represents either zero or two: b1*(2^1).
In general, bit n represents bn*(2^n).
So if you have an int x set to 5, then:
X = 5=4+1 = 1*2^2+0*2^1+1*2^0 = 101 in binary.
What's a bit shift operation?
It's an how computers shift bits left or right. Numerically, shifting the bits left is the same as multiplying by two, while shifting right is integer division by 2.
The operator << shifts bits left, and >> shifts bits right. The | operator is a bitwise OR operator, and & is a bitwise AND operator. For a great introduction to bitwise operators, refer to this excellent answer.
So if x is 5, then x<<1 is 1010b which equals = 8+0+2+0 = 10. The same as x*2.
Why should you care?
Because these macros are performing bit shift operations! So you need to understand how numbers are represented in binary to understand it.
Let's look at what those macros do!
SINE_CONTREG_BASE (0x1 << 13)
This takes the number one and shifts it left 13 times, so when this macro is used, it is replaced with the text (0x1 << 13) by CPP, and compiled as the constant value of 8196 (which is 2^0 * 2^13). So this macro is a way of documenting that the 14th bit of the SINE_CON register is important enough to have a macro which defines the value of this bit.
SINE_PHASEREG_BASE (0x3 << 14)
Similarly, this is used to represent a two-bit binary bit field in the SINE_PHASE register that can be found in bits 15 and 14 (notice that 3 is 11b).
IOPORT_MODE_MUX_MASK
This is saying that the IOPORT_MODE_MUX register is the first three bits in that register, and a MASK refers to a value, that can be used to extra those three bits using a bitwise AND operation on the value of the register. To set the values, one uses a bitwise OR operation to set the hardware bits in that register.
IOPORT_MODE_MUX_D
The IOPORT_MODE_MUX function D bits re the first two bits in that same register. You can use this macro to extract or set those two bits accordingly.

How to write and read specific bit of a 32 bit register [duplicate]

This question already has answers here:
How do I set, clear, and toggle a single bit?
(27 answers)
Closed 5 years ago.
I'm new to bit operations and trying to experiment little bit.
let's say I have a 32 bit register which is constructed as follows:
Bit 31:12 RESERVED
Bit 11 CONFIG1
Bit 10 CONFIG2
Bit 9:0 DATA
There exists already a Function to write data into the register:
#define WR_REG_32(address, value) (*((volatile u32 *)(address)) = (value))
I would like to write the value 0x0 at Bit 10 (CONFIG2). The value should be in the format like for example:
0x00005000
So, how to know what hex value to use in order to write to Bit 10 the value 0x0 without touching the other bits?
Also, what is the easiest way to read from the 32 bit register only the values from bit 0 - 9 ?
You need to read first the register to write the same bits, except the bit 10 forced to zero.
To force a bit to zero, bit 10, you have to use the bitwise AND between the current value and all-bits-to-1-except-bit-10 (zero)
newValue = currentValue & ~(1<<10)
The ~ operator invert bits. & is bitwise AND. Using the macro,
value = RD_REG_32(address) ; To read the current value
WR_REG_32(address, value & ~(1<<10))
RD_REG_32 to read the current value.
To read the bits 0~9, set the others to 0
(read value from register)
value &= 0x3FF; // keeps only the first 10 bits, from 0 to 9
Read also Eric's comment below. Your architecture might impact the way you can deal with 32 bits values.

float bit pattern in memory reversed bit-wise compared to IEEE-754?

I wrote a program to print out the bit pattern of a float number in C.
So I expected to receive a standard-IEEE-754 bit pattern i.e.:
1 sign bit | 8 EXP bits | 23 mantissa bits
when I got the output and put the result to an IEEE-754 converter the number was wrong. When I bit by bit reversed the order, the number was correct.
So why I'm asking is: I found a thread in which I learned that the pattern could be BYTE-WISE reversed, but nowhere I found it completely BIT-WISE reversed.
Can anyone claryfy on this, please?
Here's a Screenshot of the program, the output and the conversion result.
(As you can see I put the numbers into the converter in reversed order and the result looks fine to me.)
Endianness is not the issue here, since you're using a bit-shift operator on the value of the entire object.
You simply printed out the bits in the opposite order, there is nothing more than that.
You start printing least significant bits first, and the webpage starts with most significant bits. Both variants are correct.
One a side node, the way you're interpreting the float as an int is not correct and it causes undefined behavior. You should use an unsigned integer with its width equal or greater to the width of type float, and use memcpy.

Get byte - how is this wrong?

I want to get the designated byte from a 32 bit integer. I am getting wrong values but I don't know why.
The restrictions to this problem are:
Must use signed bits, and I can't use multiplication.
I specifically need to know what is wrong with the function as it's below.
Here is the function:
int retrieveByteFromWord(int word, int byte)
{
return (word >> (byte << 3)) & 0xFF;
}
ex:
(3) (2) (1) (0) ------ byte number
In word: 10010011 11001100 00110011 10101000
I want to return byte 2 (1100 1100).
retrieveByteFromWord(word, 2) ---- gives: 1100 1100
But for some cases it's wrong and it won't tell me what case.
Any ideas?
Here is the problem:
You just started working for a company that is implementing a set of procedures to operate on a data structure where 4 signed bytes are packed into a 32 bit unsigned. Bytes within the word are numbered from 0(LSB) to 3(MSB). You have been assigned the task of implementing a function for a machine using 2's complement arithmetic and arithmetic right shifts with the following prototype:
typedef unsigned packed_t
int xbyte(packed_t word, int bytenum);
This is the previous employees attempt which got him fired for being wrong:
int xbyte(packed_t word, int bytenum)
{
return (word >> (bytenum << 3)) & 0xFF;
}
A) What is wrong with the code?
B) Write a correct implementation using only left and right shifts and one subtraction.
I have done B but still don't know why A is wrong. Is it because the decimal numbers going in like 12, 15, 19, 55 and then getting packed into a word and then when I extract them they aren't the same number anymore??? It might be so I am going to run some tests real fast...
As this is homework I won't give you a full answer, but I'll point you in the right direction. Your problem statement says that:
4 signed bytes are packed into a 32 bit unsigned.
When you bitwise & a 32 bit signed integer with 0xFF the most significant bit - i.e. the sign bit - of the result is always 0, so the original function never returns a negative value regardless of the input.
By way of example...
When you say "retrieveByteFromWord(word, 2) ---- gives: 11001100" you're wrong.
Your return type is a 32 bit integer - not an 8 bit integer. You're not returning 11001100 you're returning 00000000 00000000 00000000 11001100.
To work with numbers, use signed integer types such as int.
To work with bits, use unsigned integer types such as unsigned. I.e. let the word argument be of type unsigned. That is what the unsigned types are for.
To multiply by 8, write just *8 (this does not mean that that part of the code is technically wrong, just that it is artificially contrived and needlessly unreadable).
Even better, create a self-describing name for that magic number 8, e.g. *bitsPerByte (the standard library calls it CHAR_BIT, which is not particularly self-describing nor readable).
Finally, at the design level, think about designing your functions so that the code that uses a function of yours – each call – becomes clear and readable. E.g. like int const b = byteAt( 2, x );. That can prevent bugs by e.g. preventing wrong actual argument order, and since designing for readability makes the code easier to read, it reduces time spent on that. :-)
Cheers & hth.,
Works fine for positive numbers. You may want to cast word to unsigned to make it work for integers with the MSB set.
int retrieveByteFromWord(int word, int byte)
{
return ((unsigned)word >> (byte << 3)) & 0xFF;
}

= (~0); What does it mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Is it safe to use -1 to set all bits to true?
int max = ~0; What does it mean?
Hello,
I have stumbled upon this piece of code..
size_t temp;
temp = (~0);
Anyone knows what it does?
~ is the bitwise not operator, it inverts each bit of the operand. In this case the operand is 0, so every bit is initially 0, and after applying the bitwise not every bit will be 1. The end result is you get a size_t filled with 1 bits.
sharptooth's answer is correct, but to give you more detail, the ~ is a binary operator for NOT. Basically, you're assigning the binary equivalent of NOT 0 to temp and that will set every bit to 1.
That's one way typically used to assign a size_t value built of all binary ones independent of actual size of size_t type. If that's the purpose of that code one should instead use (size_t)( -1 ).
Btw here's an identical question.
How about this?
C++ code:
#include <limits>
std::size_t temp = std::numeric_limits<std::size_t>::max();
C code:
Please take a look the question.
I think it is more proper way.

Resources