incompatability of the ternary operator - gcc

#define BIT2 (1 << 2)
#define BIT0 (1 << 0)
unsigned int a = 0, temp = 0;
#define setBit2_a (a |= BIT2)
#define clearBit2_a (a &= ~BIT2)
#define setBit0_a (a |= BIT0)
#define clearBit0_a (a &= ~BIT0)
void main()
{
a=4; //use a scanf here for convinient
temp = a;
a & BIT0 != 0 ? setBit2_a : clearBit2_a;
temp & BIT2 != 0 ? setBit0_a : clearBit0_a;
printf("the number entered is a = %u\n\r", a);
}
this should set the bit 0 in the variable a , but its not doing so in ubuntu gcc complier can anybody please explain this

Note that you probably expect a different result from your expression a & (1 << 2) != 0: the operator precedence for == is stronger than for & so the evalution results in a & ((1 << 2) != 0) which is always false for your ternary operator since 4 & 1 == 0
You want: (a & (1 << 2)) != 0 ? ...; or a & 4 ? ...;

all that is to be noted here is:
the operator precedence for == is stronger than for & so the evaluated results which is always false and we need to use the braces here in accordance with the precedence and the BODMAS rule.

Related

easy algorithm for using flags

Exists flags defs:
flag1=1
flag2=2
flag3=4
flag4=8
...
flagN=2^(N-1)
flag=flag1+flag2+...+flagN
if flagI not set, it eq 0
i have flag. which method can easily check, is for example flag2 defined?
Answer to your question
What's the range of flag? If it's under 2^64-1, almost every method is okay.
As #taskinoor posted, you should notice that:
flag1 = 000 ... ... 0001
flag2 = 000 ... ... 0010
flag3 = 000 ... ... 0100
In other words,
flag[n] = 1 << (n-1)
So, if you want to check all bits, a for loop and bitwise operation are fast enough to solve you problem. Like This (suppose you could understand C/C++ and flag is less than 2^32, which could be hold by an unsigned int in C/C++):
void check(unsigned int flag)
{
for (int i = 0; i < 32; ++i)
if ((flag & (1 << i)) != 0)
printf("flag%d defined!\n", i+1);
}
It's O(k), which k is the length of the type of flag in binary. For unsigned int, it's O(32) = O(1), almost in constant time.
If you just want to count how many flags defined:
I don't know what's your purpose. If you just want to count how many flags defined and flag is less than 2^64, the following method is awesome(suppose unsigned int as well):
unsigned int count_bit(unsigned int x)
{
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >> 16)& 0x0000FFFF);
return x;
}
If you call count_bit(1234567890), it'll return 12.
Let me explain this algorithm.
This algorithm is based on Divide and Conquer Algorithm. Suppose there is a 8bit integer 213(11010101 in binary), the algorithm works like this(each time merge two neighbor blocks):
+-------------------------------+
| 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | <- x
| 1 0 | 0 1 | 0 1 | 0 1 | <- first time merge
| 0 0 1 1 | 0 0 1 0 | <- second time merge
| 0 0 0 0 0 1 0 1 | <- third time ( answer = 00000101 = 5)
+-------------------------------+
Note that in each flag only one bit is set to 1, others are 0.
flag1 = 000 ... ... 0001
flag2 = 000 ... ... 0010
flag3 = 000 ... ... 0100
// and like this
So if you do bitwise AND flag & flag2 then the result will be non-zero only if flag2 is defined.
r = flag & flag2;
if r != 0 then flag2 is defined
You can do this with all flags.
Boolean isSet (flags, flagN){
Return (flags & flagN) != 0;
}
Flags being the flag vector, flagN the flag you want to check
It is worth grokking the concept of bitmasks and flags more deeply. You can then use your imagination to represent state efficiently . (Just an example explained below)
First -Define the bitmask : 0x0000001c
What are the binary strings for which when you do an 'and' operation on the mask, you get a non-zero value?
Those are your valid flag values.
Valid flag values for this bitmask: 0x0000001c,0x00000014,0x00000018,0x00000004,0x00000008,etc ..
So, in your application if you can do the following:
flagvariable |= flagvalue1 ->Enable a particular flag.
if( flagvariable & maskvalue) :Check if a mask is enabled :
Then the different cases you would need to check :
if(flagvariable &maskvalue ==flagvalue1) { do something}
else
if(flagvariable &maskvalue ==flagvalue2) {do something else}
flagvariable &= `flagvalue1 : Clear the flag
To be more clear about flags and bitmasks, just step into gdb and do p /t and evaluate the the operations described above.

mirror bits in char, limited operators +,<<,& no loops allowed, C language

Preparing for exam and got stuck at this question:
Allowed operators are <<,+,& no loops allowed and minimum temp variables.
Write a function in C, that gets 4-bit number (char) and returns mirrored (relative to center) bits.
Example: given b4,b3,b2,b1 return b1,b2,b3,b4
O_o thanks!
it might be not clear, but general language tools are allowed ('==',if,>,< etc..)
This is not possible given the constraints of only the operators <<, +, & and no other constructs besides return.
To move b3 from the 3rd position to the 2nd position, you will need a way to shift to the right which requires something like >> or /. Of the operators provided, none can be used with b3 to set the 2nd or 1st bit position.
if you can use if statements and the assignment operator =, it is possible. You can then write a messy solution such as
char flip(char c)
{
char f;
f = (c & 1) << 3 + (c & 2) << 1;
if (c & 4)
f = f + 2;
if (c & 8)
f = f + 1;
return f;
}
A more ugly but shorter one liner if you can use the similar to if ? operator.
char flip(char c)
{
return (c & 1) << 3 + (c & 2) << 1 + ((c & 4) ? 2 : 0) + ((c & 8) ? 1 : 0);
}

VB.NET enum declaration syntax

I recently saw a declaration of enum that looks like this:
<Serializable()>
<Flags()>
Public Enum SiteRoles
ADMIN = 10 << 0
REGULAR = 5 << 1
GUEST = 1 << 2
End Enum
I was wondering if someone can explain what does "<<" syntax do or what it is used for? Thank you...
The ENUM has a Flags attribute which means that the values are used as bit flags.
Bit Flags are useful when representing more than one attribute in a variable
These are the flags for a 16 bit (attribute) variable (hope you see the pattern which can continue on to X number of bits., limited by the platform/variable type of course)
BIT1 = 0x1 (1 << 0)
BIT2 = 0x2 (1 << 1)
BIT3 = 0x4 (1 << 2)
BIT4 = 0x8 (1 << 3)
BIT5 = 0x10 (1 << 4)
BIT6 = 0x20 (1 << 5)
BIT7 = 0x40 (1 << 6)
BIT8 = 0x80 (1 << 7)
BIT9 = 0x100 (1 << 8)
BIT10 = 0x200 (1 << 9)
BIT11 = 0x400 (1 << 10)
BIT12 = 0x800 (1 << 11)
BIT13 = 0x1000 (1 << 12)
BIT14 = 0x2000 (1 << 13)
BIT15 = 0x4000 (1 << 14)
BIT16 = 0x8000 (1 << 15)
To set a bit (attribute) you simply use the bitwise or operator:
UInt16 flags;
flags |= BIT1; // set bit (Attribute) 1
flags |= BIT13; // set bit (Attribute) 13
To determine of a bit (attribute) is set you simply use the bitwise and operator:
bool bit1 = (flags & BIT1) > 0; // true;
bool bit13 = (flags & BIT13) > 0; // true;
bool bit16 = (flags & BIT16) > 0; // false;
In your example above, ADMIN and REGULAR are bit number 5 ((10 << 0) and (5 << 1) are the same), and GUEST is bit number 3.
Therefore you could determine the SiteRole by using the bitwise AND operator, as shown above:
UInt32 SiteRole = ...;
IsAdmin = (SiteRole & ADMIN) > 0;
IsRegular = (SiteRole & REGULAR) > 0;
IsGuest = (SiteRole & GUEST) > 0;
Of course, you can also set the SiteRole by using the bitwise OR operator, as shown above:
UInt32 SiteRole = 0x00000000;
SiteRole |= ADMIN;
The real question is why do ADMIN and REGULAR have the same values? Maybe it's a bug.
These are bitwise shift operations. Bitwise shifts are used to transform the integer value of the enum mebers here to a different number. Each enum member will actually have the bit-shifted value. This is probably an obfuscation technique and is the same as setting a fixed integer value for each enum member.
Each integer has a binary reprsentation (like 0111011); bit shifting allows bits to move to the left (<<) or right (>>) depending on which operator is used.
For example:
10 << 0 means:
1010 (10 in binary form) moved with 0 bits left is 1010
5 << 1 means:
101 (5 in binary form) moved one bit to the left = 1010 (added a zero to the right)
so 5 << 1 is 10 (because 1010 represents the number 10)
and etc.
In general the x << y operation can be seen as a fast way to calculate x * Pow(2, y);
You can read this article for more detailed info on bit shifting in .NET http://www.blackwasp.co.uk/CSharpShiftOperators.aspx

What's the best way to handle an "all combinations" project?

I've been assigned a school project in which I need to come up with as many integers as possible using only the integers 2 3 4 and the operators + - * / %. I then have to output the integers with cout along with how I got that answer. For example:
cout << "2 + 3 - 4 = " << 2 + 3 - 4;
I can only use each integer once per cout statement, and there can be no duplicate answers.
Everyone else seems to be doing the "brute force" method (i.e., copying and pasting the same statements and changing the numbers and operators), but that hardly seems efficient. I figured I would try cycling through each number and operator one-by-one and checking to see if the answer has already been found, but I'm unsure of what the easiest way to do this would be.
I suppose I could use nested loops, but there's still the problem of checking to see if the answer has already been found. I tried storing the answers in a vector, but I couldn't pass the vector to a user-defined function that checked to see if a value existed in the vector.
You could use a map or a hash_map from the Standard Template Library (STL). These structures store key-value pairs efficiently. Read up on them before you use them but they might give you a good starting point. Hint: The integers you compute would probably make good keys.
Assuming you can use each of the numbers in the set(2, 3, 4) only once there are 3! ways of arranging these 3 numbers. Then there are 2 places for sign and you have total 5 symbols(+ -
* / %) so there are 5*5 = 25 ways to do that. So you have total 3! * 25 expressions.
Than you can create a hash map where key will be number and value will be the expression. If the hash map contains a key already you skip that expression.
You could try a bit of meta-programming, as follows. It has the advantage of using C itself to calculate the expressions rather than you trying to do your own evaluator (and possibly getting it wrong):
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main (void) {
int n1, n2, n3;
const char *ops[] = {" + ", " - ", " * ", " / ", " % ", 0};
const char **op1, **op2;
ofstream of;
of.open ("prog2.cpp", ios::out);
of << "#include <iostream>\n";
of << "using namespace std;\n";
of << "#define IXCOUNT 49\n\n";
of << "static int mkIdx (int tot) {\n";
of << " int ix = (IXCOUNT / 2) + tot;\n";
of << " if ((ix >= 0) && (ix < IXCOUNT)) return ix;\n";
of << " cout << \"Need more index space, "
<< "try \" << IXCOUNT + 1 + (ix - IXCOUNT) * 2 << \"\\n\";\n";
of << " return -1;\n";
of << "}\n\n";
of << "int main (void) {\n";
of << " int tot, ix, used[IXCOUNT];\n\n";
of << " for (ix = 0; ix < sizeof(used)/sizeof(*used); ix++)\n";
of << " used[ix] = 0;\n\n";
for (n1 = 2; n1 <= 4; n1++) {
for (n2 = 2; n2 <= 4; n2++) {
if (n2 != n1) {
for (n3 = 2; n3 <= 4; n3++) {
if ((n3 != n1) && (n3 != n2)) {
for (op1 = ops; *op1 != 0; op1++) {
for (op2 = ops; *op2 != 0; op2++) {
of << " tot = " << n1 << *op1 << n2 << *op2 << n3 << ";\n";
of << " if ((ix = mkIdx (tot)) < 0) return ix;\n";
of << " if (!used[ix])\n";
of << " cout << " << n1 << " << \"" << *op1 << "\" << "
<< n2 << " << \"" << *op2 << "\" << " << n3
<< " << \" = \" << tot << \"\\n\";\n";
of << " used[ix] = 1;\n\n";
}
}
}
}
}
}
}
of << " return 0;\n";
of << "}\n";
of.close();
system ("g++ -o prog2 prog2.cpp ; ./prog2");
return 0;
}
This gives you:
2 + 3 + 4 = 9
2 + 3 - 4 = 1
2 + 3 * 4 = 14
2 + 3 / 4 = 2
2 + 3 % 4 = 5
2 - 3 + 4 = 3
2 - 3 - 4 = -5
2 - 3 * 4 = -10
2 - 3 % 4 = -1
2 * 3 + 4 = 10
2 * 3 * 4 = 24
2 / 3 + 4 = 4
2 / 3 - 4 = -4
2 / 3 * 4 = 0
2 % 3 + 4 = 6
2 % 3 - 4 = -2
2 % 3 * 4 = 8
2 * 4 + 3 = 11
2 / 4 - 3 = -3
I'm not entirely certain of the wisdom of handing this in as an assignment however :-)

How can I generate this pattern of numbers?

Given inputs 1-32 how can I generate the below output?
in. out
1
1
1
1
2
2
2
2
1
1
1
1
2
2
2
2
...
Edit Not Homework.. just lack of sleep.
I am working in C#, but I was looking for a language agnostic algorithm.
Edit 2 To provide a bit more background... I have an array of 32 items that represents a two dimensional checkerboard. I needed the last part of this algorithm to convert between the vector and the graph, where the index aligns on the black squares on the checkerboard.
Final Code:
--Index;
int row = Index >> 2;
int col = 2 * Index - (((Index & 0x04) >> 2 == 1) ? 2 : 1);
Assuming that you can use bitwise operators you can check what the numbers with same output have in common, in this case I preferred using input 0-31 because it's simpler (you can just subtract 1 to actual values)
What you have?
0x0000 -> 1
0x0001 -> 1
0x0010 -> 1
0x0011 -> 1
0x0100 -> 2
0x0101 -> 2
0x0110 -> 2
0x0111 -> 2
0x1000 -> 1
0x1001 -> 1
0x1010 -> 1
0x1011 -> 1
0x1100 -> 2
...
It's quite easy if you notice that third bit is always 0 when output should be 1 and viceversa it's always 1 when output should be 2
so:
char codify(char input)
{
return ((((input-1)&0x04)>>2 == 1)?(2):(1));
}
EDIT
As suggested by comment it should work also with
char codify(char input)
{
return ((input-1 & 0x04)?(2):(1));
}
because in some languages (like C) 0 will evaluate to false and any other value to true. I'm not sure if it works in C# too because I've never programmed in that language. Of course this is not a language-agnostic answer but it's more C-elegant!
in C:
char output = "11112222"[input-1 & 7];
or
char output = (input-1 >> 2 & 1) + '1';
or after an idea of FogleBird:
char output = input - 1 & 4 ? '2' : '1';
or after an idea of Steve Jessop:
char output = '2' - (0x1e1e1e1e >> input & 1);
or
char output = "12"[input-1>>2&1];
C operator precedence is evil. Do use my code as bad examples :-)
You could use a combination of integer division and modulo 2 (even-odd): There are blocks of four, and the 1st, 3rd, 5th block and so on should result in 1, the 2nd, 4th, 6th and so on in 2.
s := ((n-1) div 4) mod 2;
return s + 1;
div is supposed to be integer division.
EDIT: Turned first mod into a div, of course
Just for laughs, here's a technique that maps inputs 1..32 to two possible outputs, in any arbitrary way known at compile time:
// binary 1111 0000 1111 0000 1111 0000 1111 0000
const uint32_t lu_table = 0xF0F0F0F0;
// select 1 bit out of the table
if (((1 << (input-1)) & lu_table) == 0) {
return 1;
} else {
return 2;
}
By changing the constant, you can handle whatever pattern of outputs you want. Obviously in your case there's a pattern which means it can probably be done faster (since no shift is needed), but everyone else already did that. Also, it's more common for a lookup table to be an array, but that's not necessary here.
The accepted answer return ((((input-1)&0x04)>>2 == 1)?(2):(1)); uses a branch while I would have just written:
return 1 + ((input-1) & 0x04 ) >> 2;
Python
def f(x):
return int((x - 1) % 8 > 3) + 1
Or:
def f(x):
return 2 if (x - 1) & 4 else 1
Or:
def f(x):
return (((x - 1) & 4) >> 2) + 1
In Perl:
#!/usr/bin/perl
use strict; use warnings;
sub it {
return sub {
my ($n) = #_;
return 1 if 4 > ($n - 1) % 8;
return 2;
}
}
my $it = it();
for my $x (1 .. 32) {
printf "%2d:%d\n", $x, $it->($x);
}
Or:
sub it {
return sub {
my ($n) = #_;
use integer;
return 1 + ( (($n - 1) / 4) % 2 );
}
}
In Haskell:
vec2graph :: Int -> Char
vec2graph n = (cycle "11112222") !! (n-1)
Thats pretty straightforward:
if (input == "1") {Console.WriteLine(1)};
if (input == "2") {Console.WriteLine(1)};
if (input == "3") {Console.WriteLine(1)};
if (input == "4") {Console.WriteLine(1)};
if (input == "5") {Console.WriteLine(2)};
if (input == "6") {Console.WriteLine(2)};
if (input == "7") {Console.WriteLine(2)};
if (input == "8") {Console.WriteLine(2)};
etc...
HTH
It depends of the language you are using.
In VB.NET, you could do something like this :
for i as integer = 1 to 32
dim intAnswer as integer = 1 + (Math.Floor((i-1) / 4) mod 2)
' Do whatever you need to do with it
next
It might sound complicated, but it's only because I put it into a sigle line.
In Groovy:
def codify = { i ->
return (((((i-1)/4).intValue()) %2 ) + 1)
}
Then:
def list = 1..16
list.each {
println "${it}: ${codify(it)}"
}
char codify(char input)
{
return (((input-1) & 0x04)>>2) + 1;
}
Using Python:
output = 1
for i in range(1, 32+1):
print "%d. %d" % (i, output)
if i % 4 == 0:
output = output == 1 and 2 or 1
JavaScript
My first thought was
output = ((input - 1 & 4) >> 2) + 1;
but drhirsch's code works fine in JavaScript:
output = input - 1 & 4 ? 2 : 1;
and the ridiculous (related to FogleBird's answer):
output = -~((input - 1) % 8 > 3);
Java, using modulo operation ('%') to give the cyclic behaviour (0,1,2...7) and then a ternary if to 'round' to 1(?) or 2(:) depending on returned value.
...
public static void main(String[] args) {
for (int i=1;i<=32;i++) {
System.out.println(i+"="+ (i%8<4?1:2) );
}
Produces:
1=1 2=1 3=1 4=2 5=2 6=2 7=2 8=1 9=1
10=1 11=1 12=2 13=2 14=2 15=2 16=1
17=1 18=1 19=1 20=2 21=2 22=2 23=2
24=1 25=1 26=1 27=1 28=2 29=2 30=2
31=2 32=1

Resources