CarryFrom operation on arm processors - arm

The Arm Architecture manual says for the ADC instruction to set the C (carry) flag in the CPSR if the S-Flag is set and a carry "occured". From the book (page 155):
C Flag = CarrryFrom(Rn + shifer_operand + C Flag)
And according to the glossar the CarryFrom is defined as follows:
CarryFrom
Returns 1 if the addition specified as its parameter caused a carry (true result is bigger
than 2^(32)−1, where the operands are treated as unsigned integers), and returns 0 in all other cases.
This delivers further information about an addition which occurred earlier in the pseudo-code. The addition is not repeated.
Now I'm wondering if the CarryForm operation is the same as an overflow check. Can anyone explain me, how I can "emulate" the CarryFrom operation or how it works?

Simply binary addition, x is the carry in to the operation and y is the carry out. For a normal add carry in is a 0 and for a normal subtract carry in is a 1. (adders are used to do subtraction, one of the features of twos complement)
y x
1111
+ 0001
======
11110
1111
+ 0001
======
0000
So the result is 0000, the carry out is a 1. Some architectures (of all of them x86, arm, mips, pdp11, 6502, ...)(yep, I know about mips in this context) invert the carry out for a subtract and leave it not inverted for addition. In this case you are asking about ADC, so that is addition so it should not be modified by any architecture.
And 4 bits or 40 does not matter it all works the same.
So if you want to add 0x0F and 0x01 but you only have a 4 bit adder (again think 64 bits and 32 instead of 8 and 4, it all works the same).
We start with normal addition of the lower bits
11110
1111
+ 0001
======
0000
Then we do an add with carry and use the carry out of the prior addition as the carry in to the second (or next one since you can do this for as much code/memory space as you have)
1
0000
+ 0000
======
00001
0000
+ 0000
======
0001
And the end result is 0x10. 0x0F + 0x01 = 0x10
The first add here happens to have an unsigned overflow as indicated by a non-zero carry out/carry flag. If you focus only on that. If the adc also had an unsigned overflow then the whole result is bad as it won't fit in the number of bits. (if the programmer considered these to be unsigned values, if signed then you look at the V bit for overflow but the Carry still cascades from the first ADD to the ADC and then from each ADC to the next until you have covered the width of the higher level operation).

Related

Can someone explains why this works to count set bits in an unsigned integer?

I saw this code called "Counting bits set, Brian Kernighan's way". I am puzzled as to how "bitwise and'ing" an integer with its decrement works to count set bits, can someone explain this?
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
Walkthrough
Let's walk through the loop with an example : let's set v = 42 which is 0010 1010 in binary.
First iteration: c=0, v=42 (0010 1010).
Now v-1 is 41 which is 0010 1001 in binary.
Let's compute v & v-1:
0010 1010
& 0010 1001
.........
0010 1000
Now v&v-1's value is 0010 1000 in binary or 40 in decimal. This value is stored into v.
Second iteration : c=1, v=40 (0010 1000). Now v-1 is 39 which is 0010 0111 in binary. Let's compute v & v-1:
0010 1000
& 0010 0111
.........
0010 0000
Now v&v-1's value is 0010 0000 which is 32 in decimal. This value is stored into v.
Third iteration :c=2, v=32 (0010 0000). Now v-1 is 31 which is 0001 1111 in binary. Let's compute v & v-1:
0010 0000
& 0001 1111
.........
0000 0000
Now v&v-1's value is 0.
Fourth iteration : c=3, v=0. The loop terminates. c contains 3 which is the number of bits set in 42.
Why it works
You can see that the binary representation of v-1 sets the least significant bit or LSB (i.e. the rightmost bit that is a 1) from 1 to 0 and all the bits right of the LSB from 0 to 1.
When you do a bitwise AND between v and v-1, the bits left from the LSB are the same in v and v-1 so the bitwise AND will leave them unchanged. All bits right of the LSB (including the LSB itself) are different and so the resulting bits will be 0.
In our original example of v=42 (0010 1010) the LSB is the second bit from the right. You can see that v-1 has the same bits as 42 except the last two : the 0 became a 1 and the 1 became a 0.
Similarly for v=40 (0010 1000) the LSB is the fourth bit from the right. When computing v-1 (0010 0111) you can see that the left four bits remain unchanged while the right four bits became inverted (zeroes became ones and ones became zeroes).
The effect of v = v & v-1 is therefore to set the least significant bit of v to 0 and leave the rest unchanged. When all bits have been cleared this way, v is 0 and we have counted all bits.
Each time though the loop one bit is counted, and one bit is cleared (set to zero).
How this works is: when you subtract one from a number you change the least significant one bit to a zero, and the even less significant bits to one -- though that doesn't matter. It doesn't matter because they are zero in the values you're decrementing, so they will be zero after the and-operation anyway.
XXX1 => XXX0
XX10 => XX01
X100 => X011
etc.
Let A=an-1an-2...a1a0 be the number on which we want to count bits and k the index of the right most bit at one.
Hence A=an-1an-2...ak+1100...0=Ak+2k where Ak=an-1an-2...ak+1000...0
As 2k−1=000..0111..11, we have
A-1=Ak+2k-1=an-1an-2...ak+1011...11
Now perform the bitwise & of A and A-1
an-1an-2...ak+1100...0 A
an-1an-2...ak+1011...1 A-1
an-1an-2...ak+1000...0 A&A-1=Ak
So A&A-1 is identical to A, except that its right most bit has been cleared, that proves the validity of the method.

distinguishes between signed and unsigned in machine code

I was reading a text book saying:
It is important to note how machine code distinguishes between signed
and unsigned values. Unlike in C, it does not associate a data type
with each program value. Instead, it mostly uses the same
(assembly)instructions for the two cases, because many arithmetic
operations have the same bit-level behavior for unsigned and
two’s-complement arithmetic.
I don't understand what it means, could anyone provide me an example?
For example, this code:
int main() {
int i = -1;
if(i < 9)
i++;
unsigned u = -1; // Wraps around to UINT_MAX value
if(u < 9)
u++;
}
gives following output on x86 GCC:
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], -1 ; i = -1
cmp DWORD PTR [rbp-4], 8 ; i comparison
jg .L2 ; i comparison
add DWORD PTR [rbp-4], 1 ; i addition
.L2:
mov DWORD PTR [rbp-8], -1 ; u = -1
cmp DWORD PTR [rbp-8], 8 ; u comparison
ja .L3 ; u comparison
add DWORD PTR [rbp-8], 1 ; u addition
.L3:
mov eax, 0
pop rbp
ret
Notice how it uses the same instructions on intialization (mov) and increment (add) for variables i and u. This is because the bit pattern changes identically for unsigned and 2's complement.
Comparison also uses the same instruction cmp, but jump decision has to be different, because values where the highest bit is set are different on the types: jg (jump if greater) on signed, and ja (jump if above) on unsigned.
What instructions are chosen, depends on the architecture and the compiler.
On Intel Processors (x86 family) and others that have FLAGS, you get bits in those FLAGS that tell you how the last operation worked. The name of the FLAGS vary a little between processors, but in general you have two important ones in regard to arithmetic: CF and OF.
CF is the Carry bit (often called C on other processors).
OF is the Overflow bit (often called V on other processors).
More or less, CF represents an unsigned overflow and OF represents a signed overflow. When the processors does the ADD operation, it has one extra bit, which is CF. So, if you add two 64 bit numbers, the result without wrapping may need 65 bits. That is the carry. The OF flag is set to the highest bit (so bit 63 in a 64 bit number), using 3 logical operations against that bit in the two sources and the destination.
There is an example of how CF works with 4 bit registers:
R1 = 1010
R2 = 1101
R3 = R1 + R2 = 1 0111
^
+---- carry (CF)
The extra 1 doesn't fit in R3 so it gets put in the CF bit instead. As a side note, the MIPS processor does not have any FLAGS. It's up to you to determine whether a carry is generated (which you can do using XOR and such on the two sources and the destination).
However, in C (and C++), there is no verification of overflow on your integer types (at least not by default.) So in other words, the CF and OF flags are ignored for all your operations except the four compare operators (<, <=, >, >=).
As shown in the example presented by #user694733, the difference is whether a jg or ja will be used. Each of the 16 jump instructions will test various flags to know whether to jump or not. That combination is really what makes the difference.
Another interesting aspect is the difference between ADC and ADD. In one case you add with the carry and the other you don't. It's probably not used as much now that we have 64 bit computers, but to add two 64 bit numbers with a 32 bit processor, it would add the lower 32 bits as unsigned 32 bit numbers and then add the upper 32 bit numbers (signed or unsigned as may be the case) plus the carry from the first operation.
Say you have two 64 bit numbers in 32 bit registers (ECX:EAX and EDX:EBX), you would add them like this:
ADD EAX, EBX
ADC ECX, EDX
Here the EDX and the carry are added to ECX if EAX + EBX had an unsigned overflow (carry--meaning that adding EAX and EBX properly should be represented by 33 bits now because the result doesn't fit 32 bits, the CF flag is that 33rd bit).
To be noted, the Intel processors have:
A Zero bit: ZF (whether the result is zero or not,)
CF is called "Borrow" when subtracting (for SBC, SBB,) and
Also the AF bit which is used for "decimal number operations" (which no one in their right mind uses.) That AF bit tells you that there is an overflow in the decimal operation. Something like that. I never used that one. I find their use too complicated/cumbersome. Also, the bit is sill there in amd64 but the instructions setting it were removed (see DAA for example).
The beauty of twos complement is that for addition (and as a result subtraction since that uses an adder, again part of the beauty of twos complement). That the add operation itself does not care about signed vs unsigned the same bit patterns added together produce the same result 0xFE + 0x01 = 0xFF, -2 + 1 = 1 also 126 + 1 = 127. same input bits same result pattern.
Twos complement helps for only a percentage. Not all. add/subtract but not necessarily multiply and divide. Bitwise of course bits is bits. But (right) shifts desire a difference, but does C deliver?
The comparisons are very sensitive. The equal and not equal, zero and not zero those are single flag tests and will work. But unsigned less than and signed less than are not the same set of flags that are used/tested. The less than and greater than with or without equal applied to them do not work the same way with unsigned vs signed. Likewise signed overflow and unsigned overflow (often just called the carry bit) are computed differently from each other. And some instruction sets the carry bit is inverted when the operand is a subtract, but not always, so for comparisons you need to know whether or not it is a borrow bit on subtract or always just the carry out unmodified.
Multiplication and likely division are "it depends". An N bit times N bit equals N bit result signed and unsigned both work, but N bit times N bit equals 2*Nbit (the only really useful hardware multiply) requires a signed and unsigned version to have the hardware/instruction do all the work, otherwise you have to break the operands up into parts if you don't have both flavors. A simple paper and pencil grade school will show why, leave that to the reader to figure out.
You don't need us at all you can easily provide your own example and see from the compiler output when there is a difference and when there isn't.
int32_t fun0 ( int32_t a, int32_t b ) { return a+b; }
int32_t fun1 ( int32_t a, int32_t b ) { return a*b; }
int32_t fun2 ( int32_t a, int32_t b ) { return a^b; }
uint32_t fun3 ( uint32_t a, uint32_t b ) { return a+b; }
uint32_t fun4 ( uint32_t a, uint32_t b ) { return a*b; }
uint32_t fun5 ( uint32_t a, uint32_t b ) { return a^b; }
uint32_t fun6 ( uint64_t a, uint64_t b ) { return a+b; }
uint32_t fun7 ( uint64_t a, uint64_t b ) { return a*b; }
uint32_t fun8 ( uint64_t a, uint64_t b ) { return a^b; }
uint64_t fun9 ( uint64_t a, uint64_t b ) { return a*b; }
int64_t fun10 ( int64_t a, int64_t b ) { return a*b; }
uint64_t fun11 ( uint32_t a, uint32_t b ) { return a*b; }
int64_t fun12 ( int32_t a, int32_t b ) { return a*b; }
int32_t comp0 ( int32_t a, int32_t b ) { return a<b; }
uint32_t comp1 ( uint32_t a, uint32_t b ) { return a<b; }
plus other operators and combinations.
EDIT
Okay the real answer...rather than making you do the work.
I want to add -2 and +1
11111110
+ 00000001
============
finish it
00000000
11111110
+ 00000001
============
11111111
-2 + 1 = -1
What about 127 + 1
00000000
11111110
+ 00000001
============
11111111
hmmm...same bits in same bits out, but how I interpret those bits as a programmer varies widely.
You can try as many legal values as you want (ones that don't overflow the result) and you will see that the addition result does not know nor care about signed vs unsigned operants. Part of the beauty of twos complement.
Subtraction is just addition in logic, some may have learned "invert and add one" want to know what the bit pattern 11111111 is you invert 00000000 and add 1 00000001 so 11111111 is -1. But how does addition really work with two operands as shown above you really need a three bit adder three bits in and two bits out the result and carry out, so there is a carry in, two operand bits a result and carry out. What if we go back to grade school as well...
-32 - 3 = (-32) + (-3) apply the invert and add one to the -3 and we get (-32) + (~3) + 1
1
11100000
+ 11111100
==============
and thats how a computer does that math, inverts the carry in and the second operand. SOME invert the carry out because a 1 on carry out when the adder is used as a subtractor means no borrow, but a 0 means a borrow happened. so some instruction sets will invert the carry out some will not. this is hugely important for this topic.
Likewise the carry out bit is computed based on the addition of the msbits of the operands and the carry in to that position, it is the carry out of that addition.
abcxxxxxx
dxxxxxxx
+ exxxxxxx
============
f
a the carry out is the carry out when adding bits b+d+e. This is also known as the unsigned overflow flag when this is an addition operation and the operands are considered to be unsigned values. But the signed overflow flag is determined by whether b and a are equal or not equal.
In what situations does this happen.
bde af
000 00
001 01
010 01
011 10 <--
100 01 <--
101 10
110 10
111 11
so you can read that is carry in is not equal to carry out for the msbit there is a signed overflow. At the same time you can say if the msbit of the operands are equal and the msbit of the result is not equal to those operand bits then signed overflow is true. If you generate a table of signed numbers and their results and which overflow this will start to be clear, you don't have to do 8 bit by 8 bit 256 * 256 combinations, take 3 or 4 bit numbers synthesize your own addition routines that or 3 or 4 bits and that smaller number of combinations will be enough.
So while addition and subtraction themselves as far as the result bits go do not know signed from unsigned the flags if you have a processor that uses them the C or carry flag the V or overflow flag have a signed based use case. The carry flag itself can have of two definitions when produced by a subtract depending on the instruction set and since comparisons are generally done with a subtraction that carry definition matters to how the flags are then used.
Greater than or less than while using a subtract to determine how they are used and the result itself is not affected by signedness how the flags are interpreted very much are.
Take some four bit positive numbers.
1101 - 1100 (13 - 12)
1100 - 1100 (12 - 12)
1011 - 1100 (11 - 12)
11111
1101
+ 0011
=======
0001
carry out 1, zero flag 0, v = 0, n = 0
11111
1100
+ 0011
========
0000
carry out 1, zero flag 1, v = 0, n = 0
00111
1011
+ 0011
========
1111
carry out 0, zero flag 0, v = 0, n = 1
(n is the msbit of the result, the sign bit 1 means signed negative number, zero means signed positive number)
cz
10 greater than but not equal
11 equal
00 less than but not equal
same bit patterns
1101 - 1100 (-3 - -4)
1100 - 1100 (-4 - -4)
1011 - 1100 (-5 - -4)
cz
10 greater than but not equal
11 equal
00 less than but not equal
so far nothing changed.
but if I examine all the combinations
#include <stdio.h>
int main ( void )
{
unsigned int ra;
unsigned int rb;
unsigned int rc;
unsigned int rx;
unsigned int v;
unsigned int n;
int sa,sb;
for(ra=0;ra<0x10;ra++)
for(rb=0;rb<0x10;rb++)
{
for(rx=8;rx;rx>>=1) if(rx&ra) printf("1"); else printf("0");
printf(" - ");
for(rx=8;rx;rx>>=1) if(rx&rb) printf("1"); else printf("0");
rc=ra-rb;
printf(" = ");
for(rx=8;rx;rx>>=1) if(rx&rb) printf("1"); else printf("0");
printf(" c=%u",(rc>>4)&1);
printf(" n=%u",(rc>>3)&1);
n=(rc>>3)&1;
if((rc&0xF)==0) printf(" z=1"); else printf(" z=0");
v=0;
if((ra&8)==(rb&8))
{
if((ra&8)==(rc&8)) v=1;
}
printf(" v=%u",v);
printf(" (%2u - %2u)",ra,rb);
sa=ra;
if(sa&8) sa|=0xFFFFFFF0;
sb=rb;
if(sb&8) sb|=0xFFFFFFF0;
printf(" (%+2d - %+2d)",sa,sb);
if(rc&0x10) printf(" C ");
if(n==v) printf(" NV ");
printf("\n");
}
}
you can find fragments within the output that show the problem.
0000 - 0110 = 0110 c=1 n=1 z=0 v=0 ( 0 - 6) (+0 - +6) C
0000 - 0111 = 0111 c=1 n=1 z=0 v=0 ( 0 - 7) (+0 - +7) C
0000 - 1000 = 1000 c=1 n=1 z=0 v=0 ( 0 - 8) (+0 - -8) C
0000 - 1001 = 1001 c=1 n=0 z=0 v=0 ( 0 - 9) (+0 - -7) C NV
0000 - 1010 = 1010 c=1 n=0 z=0 v=0 ( 0 - 10) (+0 - -6) C NV
0000 - 1011 = 1011 c=1 n=0 z=0 v=0 ( 0 - 11) (+0 - -5) C NV
For unsigned 0 is less than 6,7,8,9... so the carry out is set so that means greater than. But the same bit patterns signed 0 is less than 6 and 7 but greater than -8 -7 -6 ...
What is not obvious necessarily until you stare at it a lot or just cheat and look at ARMs documentation for signed if N == V it is a signed greater than or equal. for N != V it is a signed less than. don't need to examine the carry out. particularly the signed bit pattern problems 0000 and 1000 don't work with the carry like other bit patterns.
Hmm, I wrote this all up in other questions before. Anyway, multiply both does and doesn't care about unsigned and signed.
Using your calculator 0xF * 0xF = 0xE1. The biggest 4 bit number times the biggest 4 bit number gives an 8 bit number, we need twice as many bits to cover all the bit patterns.
1111
* 1111
=================
1111
1111
1111
+ 1111
=================
11100001
so we see the addition that results is at least 2n-1 bits, if you end up with a carry off that last bit then you end up with 2n bits.
but, what is -1 * -1? its equal to 1 right? what are we missing?
unsigned has implied zeros
00001111
* 1111
=================
00001111
00001111
00001111
+00001111
=================
00011100001
but signed the sign is extended
11111111
* 1111
=================
11111111
11111111
11111111
+11111111
=================
00000000001
so sign matters with multiply?
0xC * 0x3 = 0xF4 or 0x24.
#include <stdio.h>
int main ( void )
{
unsigned int ra;
unsigned int rb;
unsigned int rc;
unsigned int rx;
int sa;
int sb;
int sc;
for(ra=0;ra<0x10;ra++)
for(rb=0;rb<0x10;rb++)
{
sa=ra;
if(ra&8) sa|=0xFFFFFFF0;
sb=rb;
if(rb&8) sb|=0xFFFFFFF0;
rc=ra*rb;
sc=sa*sb;
if((rc&0xF)!=(sc&0xF))
{
for(rx=8;rx;rx>>1) if(rx&ra) printf("1"); else printf("0");
printf(" ");
for(rx=8;rx;rx>>1) if(rx&rb) printf("1"); else printf("0");
printf("\n");
}
}
}
and there is no output. as expected. the bits abcd * 1111
abcd
1111
===============
aaaaabcd
aaaaabcd
aaaaabcd
aaaaabcd
================
four bits in on each operand if I only care about the lower four bits out
abcd
1111
===============
abcd
bcd
cd
d
================
how the operand sign extends does not matter as far as the result is concerned
Now knowing that a significant portion of the possible combinations of n bit times n bit equals n bit overflow it doesnt help you much to do such a thing in any code you want to be useful.
int a,b,c;
c = a * b;
not very useful except for smaller numbers.
But the reality is as far as multiply if the result is the same size as the operands then signed vs unsigned does not matter, if the result is the proper twice the size of the operands then you need a separate signed multiply instruction/operation and an unsigned. You can certainly cascade/synthesize the nn=2n with an nn=n instruction as you will see in some instruction sets.
bitwise operands, xor, or, and, these are bitwise they dont/cant care about sign.
shift left start with abcd shift one bcd0, shift two cd00 and so on. not very interesting. Shift right though desires to have separate arithmetic and logical shift right where arithmetic the msbit is duplicated as the shift in bit, and logical a zero shifts in arithmetic abcd aabc aaab aaaa, logical abcd 0abc 00ab 000a 0000
But we dont have two kinds of shift right in C. But when doing addition and subtraction directly, bits is bits, the beauty of twos complement. When doing a comparison which is a subtract then the flags used are different for signed vs unsigned for a number of the comparisons, get the older ARM architectural reference manual, I think they call it the armv5 one, even though it goes back to the armv4 and up to the armv6.
There is a section called "The condition field" and a table, this very nicely shows at least for the ARM flags the flag combinations for both unsigned this and that, signed this and that and the ones that dont care about signedness (equal, not equal, etc) wont say anything.
Understand/remember that some instruction sets not only invert the carry in bit and second operand on a subtract but will also invert the carry out bit. so if a carry bit is used on something signed then it is inverted. the stuff I did above where I tried to use the term carry out instead of carry flag, the carry flag would be inverted for some other instruction sets and the unsigned greater than and less than table flips over.
Division is not as easy to show, you have to do long division, etc. I will leave that one to the reader.
Not all documentation is as good as the table I am referring to in ARMs docs. Other processor documentation may or may not make the unsigned vs signed, they might just say jump if greater than and you may have to experimentally figure out what that means. Now that you now all of this you may have already figured out you dont for example need a branch if unsigned or equal. That just means branch if not less than so you can
cmp r0,r1
or
cmp r1,r0
and just use branch if carry to cover the unsigned less than, unsigned less than or equal, unsigned greater than, unsigned greater than or equal cases. Although you might upset some programmers doing that because you were trying to save some bits in the instruction.
Saying ALL of that, the processor never distinguishes signed from unsigned. These are concepts that only mean something to the programmer, processors are very stupid. Bits is bits, the processor doesnt know if these bits are an address, if they are a variable if they are a character in a string, a floating point number (being implemented with a soft float library in fixed point), these interpretations are only meaningful to the programmer not the processor. The processor does not "distinguish between unsigned and signed in machine code", the programmer has to properly place bits that are meaningful to the programmer and then select the right instructions and sequences of instructions to perform the task the programmer wants performed. Some 32 bit number in a register is only an address when those bits are used to address something with a load or store, once that one clock cycle where they are sampled to be delivered to an address bus they are an address, before and after that they are just bits. When you increment that pointer in your program they are not an address they are just bits you are adding some other bits to. You can certainly build a MIPS like instruction set with no flags, and only N bit to N bit multiplies, only have a jump if two registers are equal or not equal instruction no other greater than or less than type instructions and still be able to make useful programs just like instruction sets that go overboard with those things unsigned this flag and signed that flag, unsigned this instruction and signed that instruction.
A not so popular but sometimes talked about in school, maybe there was a real instruction set or many that did this is a non-twos complement solution and that pretty much means sign and magnitude a sign bit and an unsigned value so +3 is 0011 and -3 is 1011 for a four bit register that burns one bit for sign when doing signed math. You then as with twos complement have to sit down with pencil and paper and work through the math operations, grade school style, then implement those in logic. Does this result in a separate unsigned and signed add? twos complement 4 bit registers we can do 0-15 and -8 to +7 for sign magnitude we can declare unsigned is 0 - 15 but signed is -7 to +7. An exercise for the reader, the question/quote had to do with twos complement.
Check out Two's Complement and its arithmetic operations, it is signed numbers in binary.
Two's complement is the most common method of representing signed
integers on computers. In this scheme, if the binary number 010(2)
encodes the signed integer 2(10), then its two's complement, 110(2),
encodes the inverse: -2(10). In other words, to reverse the sign of any
integer in this scheme, you can take the two's complement of its
binary representation.
That way it is possible to have arithmetic operations between positive and negative binary values.
Two's Complement Python code snippet:
def twos_complement(input_value, num_bits):
'''Calculates a two's complement integer from the given input value's bits'''
mask = 2**(num_bits - 1)
return -(input_value & mask) + (input_value & ~mask)

What is the purpose of "ts & 0xffff0000"?

I'm working on a real time protocol that adding the timestamp for each transmitted packet and I don't understand what the lines of code mean. Thanks for help.
// ts for timestamp
unsigned int ts;
if(ts & 0xffff0000){
// do something
}
Given the fact they're using binary-and (&), the intent seems to be to check if any of the 16 high bits are set.
Binary-and examines the bits at each position in both numbers, and if they're both 1, then the result as a 1 bit in that same position. Otherwise the result has a zero in that position
0b 001001001001001001001001001001 (first number, usually a variable)
0b 010101010101010101010101010101 (second number, usually a "mask")
=================================
0b 000001000001000001000001000001 (result)
If this is used as the condition of an if-block, such as if (x & mask), then the if-block is entered if x has any of the same bits as mask set. For 0xFFFF0000, the block will be entered if any of the high 16 bits are set.
That is effectively the same as if (ts > 65535) (if int is 32bit or less), but apparently the intent is to deal with bits, rather than the actual value.
0xffff0000 serves as a bit mask here.
ts & 0xffff0000 satisfies as a condition when some bit in the first 16 bits of ts is 1. Put another way, when ts >= 2^16.
This IF loop checks if any of upper 16 bits of ts is high. If yes, then loop is executed.
The IF loop is executed only if ts >= 0x00010000.
An intuitive way to understand this.
**** **** **** **** //the first 16bits of ts
& 1111 1111 1111 1111 //the first 16bits of 0xffff 0000
If one of the first 16bits of ts is set, then the result above won't be zero.
If they are all 0, the result above will be 0000 0000 0000 0000
For the last 16bits of ts, no matter what happens to these bits, the result of Binary-and will be 0.
**** **** **** ****
& 0000 0000 0000 0000
=0000 0000 0000 0000
So if the first 16 bits of ts have one 1 bit ==> ts&0xffff0000 > 0 (which means ts>=0b 10000 0000 0000 0000(i.e., 2^16)), el se ts&0xffff0000 == 0.
Always, we also use this ts&1 to test whether ts is an odd number.

How to set and clear bits without ~ operator

I am using a C like script for Bluegiga chip and their scripting langauge does not have the ~ operator in the compiler.
Is there any way to work with bits using pure math?
For example i read a byte and i need to clear bit 1 and set bit 2.
The following bitwise operations are supported:
Operation Symbol
AND &
OR |
XOR ^
Shift left <<
Shift right >>
The following mathematical operators are supported:
Operation Symbol
Addition: +
Subtraction: -
Multiplication: *
Division: /
Less than: <
Less than or equal: <=
Greater than: >
Greater than or equal: >=
Equals: =
Not equals: !=
Just use OR and AND operations. To do that operation:
initial byte: 0000 0001
clear bit 1: 0000 0001 & 1111 1110 --> result - 0000 0000 (The 1st bit of the second operand must be 0 to clear the bit)
now set bit 2: 0000 0000 | 0000 0010 --> result - 0000 0010 (The 2st bit of the second operand must be 1 to set the bit)
Note that for this operations you only change the specific bit all the other remain with the same value.
Also to obtain the second operand you can just obtain it by:
for the set operation on the n bit - the second operand is 2^n
for the clear operation on the n bit - the second operand is 1111 1111 XOR 2^n (in this case 1111 1111 XOR is used for the not operation).
If you are missing the ~ operator, you can make your own using XOR and a constant.
#include<stdio.h>
int main()
{
unsigned int s = 0xFFFFFFFF ;
printf("%#x" , 0xFF ^ s ) ; //XOR with the constant is equivalent to ~
unsigned int byte = 0x4 ;
printf("%#x" , 0x5 & ( byte ^ s ) ) ; //clear those bits
return 0 ;
}
When you have ~ it is easy to clear the bits.
Clearing a (single) bit is also equivalent to SET following by INVERT (or xor). Thus.
aabbccdd <-- original value
00000110 OR
00000010 XOR
--------
aabbc10d <-- result (I'm counting the bits from 7 downto 0)
This approach has the benefit of being scalable from byte to the native integer size without the burden of calculating the mask for AND operation.
Performing a XOR against -1 will invert all the bits in an integer.

Why does the following bitwise operation return an unintended result?

3 bits can hold up to a maximum number of 7 (4 + 2 + 1). I'm trying to calculate this using a bitwise operation.
3 is 0b011
~3 is 0b100
Doing a bitwise OR I would expect 0b111 (i.e. 7). Instead I get
int result = (~3) | 3;
printf("%i\n", result);
-1
What am I doing wrong?
You are doing everything right: N | ~N results in a number with binary representation consisting of all ones. Such number is interpreted as -1 in two's compliment representation of negative numbers.
How many bits wide is an int? You seem to think it's three bits wide. Certainly not correct! Guess again. What is ~0u? Try printf("%u\n", ~0u);. What about ~1u? ... and ~2u? Do you notice a pattern?
Note the u suffix, which tells the compiler that it's an unsigned literal. You can't work with signed integer types with the ~ operator... Well, you can, but you might run into trap representations and negative zeros, according to 6.2.6.2 of n1570.pdf. Using a trap representation is undefined behaviour. That might work on your system, but only by coincidence. Do you want to rely upon coincidence?
Similarly, I suggest using the %u directive to print unsigned values, as %d would produce undefined behaviour according to 7.21.6.1p29 of n1570.pdf.
When you do ~3 you are inverting the bits that make up 3 - so you turn 0000 0000 0000 0000 0000 0000 0000 0011 into 1111 1111 1111 1111 1111 1111 1111 1100. Since the high bit is set, this is interpreted as a negative number - all 1s is -1, one less than that is -2, one less -3 and so on. This number is the signed 32 bit integer for -4.
If you binary OR this with 3, you get all 1s (by definition) - which is the signed 32 bit integer for -1.
Your only problem is that you think you are working with 3 bit numbers, but you are actually working with 32 bit numbers.
After doing this in the code
int result = (~3) | 3;
Add this line
result= result & 0x07
This will give you the answer that you expect.
#include <stdio.h>
int main (){
unsigned d3 = 0b011;
unsigned invd3 = ~d3;
unsigned d4 = 0b100;
unsigned result = d3 | invd3;
printf("%X\n", result);//FFFFFFFF
result = d3 | d4;
printf("%X\n", result);//7
return 0;
}

Resources