This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Sunday 2 February 2014

How do you set, clear and toggle a single bit in C/C++?

Setting a bit
Use the bitwise OR operator (|) to set a bit.
number |= 1 << x;
That will set bit x.
Clearing a bit
Use the bitwise AND operator (&) to clear a bit.
number &= ~(1 << x);
That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
Toggling a bit
The XOR operator (^) can be used to toggle a bit.
number ^= 1 << x;
That will toggle bit x.
Checking a bit
You didn't ask for this but I might as well add it.
To check a bit, AND it with the bit you want to check:
bit = number & (1 << x);
That will put the value of bit x into the variable bit.

Why does printf not flush after the call unless a newline is in the format string?

The stdout stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:
Print to stderr instead using fprintf:
fprintf(stderr, "I will be printed immediately");
Flush stdout whenever you need it to using fflush:
printf("Buffered, will be flushed");
fflush
(stdout); // Will now print everything in the stdout buffer
Edit: From Andy Ross's comment below, you can also disable buffering on stdout by using setbuf:
setbuf(stdout, NULL);

Best way to detect integer overflow in C/C++

There is a way to determine whether an operation is likely to overflow, using the positions of the most-significant one-bits in the operands and a little basic binary-math knowledge.
For addition, any two operands will result in (at most) one bit more than the largest operand's highest one-bit. For example:
bool addition_is_safe(uint32_t a, uint32_t b) {
size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);
return (a_bits<32 && b_bits<32);
}
For multiplication, any two operands will result in (at most) the sum of the bits of the operands. For example:
bool multiplication_is_safe(uint32_t a, uint32_t b) {
size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);
return (a_bits+b_bits<=32);
}
Similarly, you can estimate the maximum size of the result of a to the power of b like this:
bool exponentiation_is_safe(uint32_t a, uint32_t b) {
size_t a_bits=highestOneBitPosition(a);
return (a_bits*b<=32);
}
(Substitute the number of bits for your target integer, of course.)
I'm not sure of the fastest way to determine the position of the highest one-bit in a number, here's a brute-force method:
size_t highestOneBitPosition(uint32_t a) {
size_t bits=0;
while (a!=0) {
++bits;
a
>>=1;
};
return bits;
}
It's not perfect, but that'll give you a good idea whether any two numbers could overflow before you do the operation. I don't know whether it would be faster than simply checking the result the way you suggested, because of the loop in the highestOneBitPosition function, but it might (especially if you knew how many bits were in the operands beforehand).

what is array decaying?

It's said that arrays "decay" into pointers. A C++ array declared as int numbers[5] cannot be re-pointed, i.e. you can't say numbers = 0x5a5aff23.
When you pass an array into a function, either directly or with an explicit pointer to that array, it has decayed functionality, in that you lose the ability to call sizeof() on that item, because it essentially becomes a pointer. This is why it's preferred to pass by reference (among other reasons).
Three ways to pass in an array:
void by_value(const T array[])
void by_pointer(const T* const array)
void by_reference(const T (&array)[U])
Only the last, the reference example, will give proper sizeof() info.
Edited to add: Note: it's not really "by value", just idiomatically so. The purpose of the three functions is to show the various "techniques" which don't maintain the full functionality of an array, i.e. sizeof(), but instead lead to "decay".

Can you write object oriented code in C?

Since you're talking about polymorphism then yes, you can, we were doing that sort of stuff years before C++ came about.
Basically you use a struct to hold both the data and a list of function pointers to point to the relevant functions for that data.
So, in a communications class, you would have an open, read, write and close call which would be maintained as four function pointers in the structure, alongside the data for an object, something like:
typedef struct {
int (*open)(void *self, char *fspec);
int (*close)(void *self);
int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
// And data goes here.
} tCommClass;

tCommClass commRs232
;
commRs232
.open = &rs232Open;
: :
commRs232
.write = &rs232Write;

tCommClass commTcp
;
commTcp
.open = &tcpOpen;
: :
commTcp
.write = &tcpWrite;
Of course, those code segments above would actually be in a "constructor" such as rs232Init().
When you 'inherit' from that class, you just change the pointers to point to your own functions. Everyone that called those functions would do it through the function pointers, giving you your polymorphism:
int stat = (commTcp.open)(commTcp, "bigiron.box.com:5000");
Sort of like a manual vtable.
You could even have virtual classes by setting the pointers to NULL -the behaviour would be slightly different to C++ (a core dump at run-time rather than an error at compile time).
Here's a piece of sample code that demonstrates it. First the top-level class structure:
#include <stdio.h>

// The top-level class.

typedef struct _tCommClass {
int (*open)(struct _tCommClass *self, char *fspec);
} tCommClass;
Then we have the functions for the TCP 'subclass':
// Function for the TCP 'class'.

static int tcpOpen (tCommClass *tcp, char *fspec) {
printf
("Opening TCP: %s\n", fspec);
return 0;
}
static int tcpInit (tCommClass *tcp) {
tcp
->open = &tcpOpen;
return 0;
}
And the HTTP one as well:
// Function for the HTTP 'class'.

static int httpOpen (tCommClass *http, char *fspec) {
printf
("Opening HTTP: %s\n", fspec);
return 0;
}
static int httpInit (tCommClass *http) {
http
->open = &httpOpen;
return 0;
}
And finally a test program to show it in action:
// Test program.

int main (void) {
int status;
tCommClass commTcp
, commHttp;

// Same 'base' class but initialised to different sub-classes.

tcpInit
(&commTcp);
httpInit
(&commHttp);

// Called in exactly the same manner.

status
= (commTcp.open)(&commTcp, "bigiron.box.com:5000");
status
= (commHttp.open)(&commHttp, "http://www.microsoft.com");

return 0;
}
This produces the output:
Opening TCP: bigiron.box.com:5000
Opening HTTP: http://www.microsoft.com

Twitter Delicious Facebook Digg Stumbleupon Favorites More