atrium wrote:
Particularly if code has to be re-implemented on a different platform or in a different language, different approaches can be very useful.
|
This, a think, is a very good idea. And I think, also Agonche could find it very interesting.
atrium wrote:
start again from scratch, in the real world, that won't always be possible |
You are right about this. And we also wouldn't like to invent the wheel new. We can simply use, what our compiler and the libraries offer.
But we also should know, what simple expressions mean on different systems, and about people normally wouldn't think about, because they simply use, what they have, without any questioning. And what is clumsy or not, depends much, of the system, whe use. For example:
a << 1
That is never clumsy, each micro processor can do this.
But what about:
a << n
Micro processors, as we have in our PC can do this. Maybe << 8 needs more time, as << 1. This difference could be important, if we need the highest speed, whe can get.
But what about a << n, if the micro processor don't understand a << n, but only a << 1?
Then we should think of a function ShiftLeft:
1 2 3 4 5
|
unsigned int ShiftLeft( unsigned int a, unsigned char n)
{
for( int i = 0; i < n ; ++i) a <<= 1;
return a;
}
|
This code would not perform so very well.
And if we only would have a system with 8 bit data?
First lets try a function for only a << 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
unsigned int ShiftLeft1( unsigned int a)
{
unsigned char * input = &a;
unsigned int ReturnValue;
unsigned char * output = &ReturnValue;
// ========= Your Code ============
// you may use: << 1 , unsigned char
// you may not use << n, other data types except uchar
// you may not use / (Division), * (Multiplikation), % (modulo)
// ==============================
return ReturnValue;
}
|
The we try to implement the following function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
unsigned int ShiftLeft( unsigned int a, unsigned char n)
{
unsigned char * input = &a;
unsigned int ReturnValue;
unsigned char * output = &ReturnValue;
// ========= Your Code ============
// you may use: << 1 , unsigned char
// you may not use << n, other data types except unsigned char
// you may not use / (Division), * (Multiplikation), % (modulo)
// ==============================
return ReturnValue;
}
|
And because I think of this difference, I always use a << 1, when I don't need a << n
And why such functions? We don't need them, because the compiler translate it, but we also should think about what the compiler does.
This topic is a very interesting one. But most programmers seem to know nearly nothing about it.
And you need knowledge about bits and bytes especially for hardware near programming.