tux4life 2,072 Postaholic

This is a portable implementation for converting a character or an integer to its binary text equivalent.
It makes use of the CHAR_BIT constant (which is defined in the header file climits) to get the number of bits a byte consists of on the implementation where you compile this code on.
Further for simplicity, it makes use of STL: bitset :)
To understand how the program works, I advise you to just compile and run it.
When you run the program, it will ask you to enter a character
(or an integer, in case you're running the integer converter).
After you've pressed the ENTER key, the program will display the corresponding binary value.
I've also supplied some sample output, in case you're not be able to compile the code directly, you could take a look at that first.

tux4life 2,072 Postaholic

As it now stands, I really have to admit that this code sucks.

tux4life 2,072 Postaholic

Instead of checking for [B]NOTOK[/B] in the [B]get_token()[/B] function, I had better made them into [B]else if[/B] .

tux4life 2,072 Postaholic

It might be better to implement a separate function to check whether a string is valid or not.

tux4life 2,072 Postaholic

I didn't know what to do and I thought: why not try writing an interpreter, I've never done this before and it seemed quite challenging, so I started writing code....

The code which you can find below is only a simple base upon which you can start implementing your own simple programming language.
(Yet to mention: the code doesn't feature an expression parser or variables, so you'll have to implement that yourself)

As this is my first time I do a programming challenge like this one, it can of course be that there are several improvements possible in my code, I'd be glad if you could improve me at some point(s).

For simplicity (and testing) I've only implemented two functions :P: PRINT and END (they're both written in uppercase, and the interpreter will report a syntax error if you don't write them like that)

Description of the two built-in functions:

  • PRINT: Print some text (or a number) to the screen, only one token at a time is allowed, supported tokens are: STRING and NUMBER (where STRING is anything you can type on your keyboard (as long as it's in between two quotes) and NUMBER can be any valid integer (floating point numbers aren't supported), the output is always ended with a newline character.
  • END: This function signals the end of the program and shuts down the interpreter.
tux4life 2,072 Postaholic

First of all: my intention was to write a program which just lets the user enter a password, while displaying an asterisk for each character entered (correction through backspace allowed).

However you're right in saying that this program is not secure, because the password is hardcoded, but it was never my intention that my program would be used as it's displayed here for 'serious' programs.
I included a variable, which contains a hardcoded password, with the only purpose to be able to demonstrate this little program.

People here are free to copy my code and modify it according to their needs, if they want to enhance security by using hashed passwords, that's okay.

Using hashing, you'll have to do something like this in general:

  1. Get the hashed password.
  2. Get the user entered password.
  3. Hash the password entered by the user and compare it to the hashed (correct) password.
    If the comparison yields true, then log the user in.
tux4life 2,072 Postaholic

>If you pretend this to be valid C++ totally FAIL.
Well, in fact this is all valid C++, with the minor exception that I used an unportable library, but does that make it invalid C++ code?
The code is not standard C++ (but that's only because I used the conio library).
BTW, I posted this snippet in the C section of code snippets and not in the C++ section, but it should work on most C++ compilers as well (as long as they support conio.h).
When you intend to compile this code on a C++ compiler, then you should of course change the include directives to include the new-style headers, because most compilers only provide the old-style headers for backwards compatibility and because therefore they're not standard.
And if you want, you can always use the C++ iostream class library for I/O.
But remember that my intention was that it is C code in the first place.
Well, I would like to see you how you would do it in Standard (valid) C++.

tux4life 2,072 Postaholic

Code Improvement!
It might be a good practice to change the loop's condition,
from: while( c != 13 ); to: while( c != 13 && pos < 256); as this will avoid to go over the bounds of the buffer.
:)

tux4life 2,072 Postaholic

Bug Fix!
Change: buffer[ pos[B]--[/B] ] = '\0'; to: buffer[ [B]--[/B]pos ] = '\0'; :)

tux4life 2,072 Postaholic

One of the things which attracted my attention was that there are often newbies asking how to create a password program in C/C++, often they don't succeed, well here's my response, you can use it for any purpose you want, one thing you'll have to keep in mind is that this code will only work on compilers which support conio.h, I know that it's actually a bad habit to make use of this "library", but most of the newbies which are searching for code like this are always using a compiler which supports it, so I guess that won't be a big problem.
As compiler to compile this code I used MinGW.
(The world's best open source compiler for Windows)
You can get the command line compiler from the site, however if you're new to
C/C++ then I would rather suggest you to go and get an IDE featuring the MinGW compiler: Code::Blocks is a very good one, also often used is the Dev-C++ IDE, but there's on major disadvantage of Dev-C++: The source code editor of the IDE isn't being updated anymore (however you can still use it with the newest MinGW compiler, that would be no problem)

tux4life 2,072 Postaholic

>only works with Dev-Cpp, may not work with any other compiler
Dev-C++ isn't a compiler, it's an IDE which uses MinGW as it's compiler :P

Nice snippet!

tux4life 2,072 Postaholic

strcmp can also be written like this :D:

int strcmp(const char *s1, const char *s2) {
    while( ( *s1 && *s2 ) && ( *s1++ == *s2++ ) );
    return *( --s1 ) - *( --s2 );
}

However, I didn't include code to avoid a NULL-pointer in my code, but it might be wise to do so as well :)

tux4life 2,072 Postaholic

I'm glad to know that there was actually no need for a separate function like pow, the bit shifting is a superior method to multiplicate it every time by two!
And William, your program will threat any other value than '1' as a '0', this isn't wrong IMO, but I only wanted to let you know in case you didn't (but probably you did know this already, because you're always one step ahead :))
I learned again from your code, you're superior in writing efficient and very easy to understand code :) !!

tux4life 2,072 Postaholic

Yep, there you've got a point!
For those who are using the cmath library:
Change the name of the pow function to apow/mypow/pow2 or whatever you like :P

tux4life 2,072 Postaholic

This snippet allows you to convert a text representation(*) of a binary number to a decimal number :)

(*): With 'text representation' I mean for example a string containing "1001" or "10001110011", etc. ...

tux4life 2,072 Postaholic

Usage:: [B]ir_strcpy[/B]( [I]destination[/I], [I]source[/I], [I]range_begin[/I], [I]range_end[/I]); example:

char test[] = "Hello World!!!";
char test2[20];
ir_strcpy(test2, test, 1, 3); /* test2 now contains 'ell' */
tux4life 2,072 Postaholic

This is how mine strlen function would look like if I'd to implement it from scratch :)

tux4life 2,072 Postaholic

Hi, naply, take a look at this and you'll see that toupper only converts alphabet letters to uppercase (this is analog for tolower), I intended my code to do 'exactly' the same :)

WH>Am I good or what?
Yes, you're the best :P

tux4life 2,072 Postaholic

This is a toupper and tolower implementation for whole c-strings, without making use of the existing toupper and tolower functions for characters :)

example:

char s[]="Hello, beautiful world!";
stoupper(s); // s now contains: `HELLO, BEAUTIFUL WORLD!´
stolower(s); // s now contains: `hello, beautiful world!´
tux4life 2,072 Postaholic

Yet to mention: I didn't include a NULL-pointer check :D

tux4life 2,072 Postaholic

This is how mine strcmp function would look like if I'd to implement it from scratch :)

tux4life 2,072 Postaholic

And it's well commented and it addresses a common beginner's problem :)
Though I'm not so sure about the <string.h> you've to include, it has to be <string>, string.h contains several functions which operate on c-strings ...

Nice snippet!

tux4life 2,072 Postaholic

Or you could rewrite it in a shorter way, thanks to William Hemsworth

void mystrcat(char * s1, const char * s2)
{
    while(*s1++);
    while(*s1++ = *s2++);
}
tux4life 2,072 Postaholic

This is how mine strcat would look like if I'd have to write it from scratch :)

tux4life 2,072 Postaholic

Thanks for replying and oh, you're damned right :)
It's like I'm addicted to always use a for-loop, and in that way I practically don't use a while loop :P

tux4life 2,072 Postaholic

This is how mine strcpy would look like if I'd have to write it from scratch :)

tux4life 2,072 Postaholic

This prime number generator is based on Eratosthenes' sieve, the found prime numbers are written to a file (you can specify it's name as a command line argument, as well you can specify the prime number upper bound (e.g: if you specify 500 as upper bound, the program will find all prime numbers which are in range of 2-500) :)

tux4life 2,072 Postaholic

BTW, You can quickly adapt this code to C by just declaring i at the top of astrstr :)

Forgot to mention: The function behaves exactly as the normal strstr (so actually there was no need for a function like astrstr :P):
When the substring is found it returns a pointer to the beginning of that substring, otherwise, when the string you're searching for isn't found, it will return a NULL-pointer :)

You can change it return type from const char* to char* if there's need to, or you can overload the function.

tux4life 2,072 Postaholic

Hi, please don't blame me for reinventing the wheel, I was bored and had nothing to do, so I thought: what would I write?
And apparently this code is the result :P

tux4life 2,072 Postaholic

The op_v function can be updated, by using strchr instead.
This will compact the code with 13 lines :)

tux4life 2,072 Postaholic

This program can solve expressions of the following forms: a+b , a-b , a*b , a/b ( a and b are numbers :P)
Notice: You can't put spaces in between the operands and the operator, I know this is a limitation and that there are thousands of other ways to achieve a better result, so please don't start complaining about this, it's just a "very simple" two-operand expression 'parser' :)

tux4life 2,072 Postaholic

This is how it would look like if you asked me to rewrite it:

void reverse(char *p)
{
    char *q = p + strlen(p) - 1;

    for(; p < q; p++, q--)
    {
        char c = *p;
        *p = *q;
        *q = c;
    }
}

(no NULL-pointer check included).

tux4life 2,072 Postaholic

>_strrev() is generally provided in most compilers.
But not on all :P

tux4life 2,072 Postaholic

A small function which reverses a c-string by just swapping the elements :) ...

Usage::

char[] str = "hello";
reverse(str); // str now contains "olleh"
tux4life 2,072 Postaholic

Probably one of the poorest sorting algorithms ever written but I provide it here and anyone who wants to use it can use it in any way he/she wants :P ...

Usage: bubble_sort(your_array, number_of_elements);

int arr[] = {52,85,2,1,-56,802};
bubble_sort(arr, 6); /* order of elements in arr: {-56, 1, 2, 52, 85, 802} */
tux4life 2,072 Postaholic

>Anyway, don't mind if I post my version do you? I haven't written one yet, but I feel like writing one soon.

No problem :)

It could be that there are some functions in my code which aren't used anywhere, that's because I was rewriting parts of my code, but I've never finished it so I just posted my code and took some functions out of it but I see that I've forgot some :)

tux4life 2,072 Postaholic

>Why would someone sell your code?
>> I dunno
>>You never know, these people exist :P

tux4life 2,072 Postaholic

> I know there are some bad things in my code such as system("CLS"); and that this makes the code unportable and inefficient, but you could just remove it at anytime :)

> It could be that my code is a bit bloated, I didn't put enough time and effort in it so that's my mistake

> I know this is probably one of the million TicTacToes available on the internet, but I just wanted to contribute some (bloated?) code ...

> Any further comments are appreciated ! :)

> There's a little bug (if you can call it that way) in my code (where else LOL :P): If you play the moves in a particular order you can *ALWAYS* win the game against the computer :P, this can easily be fixed by implementing a function which plays random moves :)

> My goal: provide understandable code

> I hope you will enjoy :P !

tux4life 2,072 Postaholic

I've also written such a snippet like this (I haven't posted it though :P)
Nice and well commented :) ...

tux4life 2,072 Postaholic

MosaicFuneral>...and conio.h doesn't exist on most compilers
Actually I don't know a compiler where it doesn't exist, can you give me an example of this?

I only know the ones which are supporting it: Digital Mars compiler, OpenWatcom, Borland C++ Compiler, MinGW, I'm not sure whether the M$ compiler's support this :P

WH>You can't backspace your password
True, that's actually a very unpleasant user experience, but he can implement it :)

WH>Doesn't compile for me, 'prinft' isn't a function
He meant printf of course :P ...

WH>Shouldn't use 'clrscr()'
Agreed

WH>Shouldn't use 'void main'
Absolutely right!

saroj_timsina>its assom
No it isn't, it lacks the capability to use backspace to correct a typo ...

tux4life 2,072 Postaholic

The next step should be an expression parser, which isn't just evaluating expressions of type x+y, x-y, x*y and x/y (and where you can just enter the whole expression in one time), but also accepts brackets '(' ')' and is just evaluating any type of expressions (bearing in mind that the supported operations are: +,-,*,/ :) ...

tux4life 2,072 Postaholic

Nice snippet, but the usage of assembler code makes it unportable :) ...

tux4life 2,072 Postaholic

Wow, nice advice ! :)

tux4life 2,072 Postaholic

If you also need subtraction, multiplication and division for hexadecimal number you only have to change the sign in the return instruction of the hexadd-function from '+' to -, *, /

...

tux4life 2,072 Postaholic

I've written a program to add two hexadecimal numbers ...

Njoy !

tux4life

tux4life 2,072 Postaholic

It works but I think it isn't very understandable anymore :P ...

tux4life 2,072 Postaholic

Here's the final code of my itos-function, and you can see that I've completely rewritten it :) :

string itos(int a) {
	string sign = a<0?"-":"";
	string result = a>0?string(1,(a%10+'0')):string(1,((a=-a)%10+'0'));
	(a/=10)>0?result=itos(a)+result:result;
	return sign+result;
}

The ternary operator is my friend :P !!!

tux4life 2,072 Postaholic

Yeah, you're right William, but I was planning to rewrite the whole code for the reason you mentioned ...
My fixed code would also have used the modulo operator
(in that way I can finally get rid of that apow-function :P)

Nice to know is that I actually forgot to make it 'negative number'-friendly, thanks for mentioning that :) !!

tux4life 2,072 Postaholic

I know you can achieve the same using string streams, but my goal was to do without ...

Still thanks for your reply !

tux4life 2,072 Postaholic

I've written a C++ function which converts an integer to a (C++-)string ...

...
string s = itos(5698);
cout << s << endl; /* Will print '5698' on the screen */
...

You MAY use this code for anything you want but you aren't allowed to sell this source ...

Enjoy!

tux4life