atoi and itoa

atoi and iota seem like perfect partners.

atoi is the ‘ascii to integer’ function and itoa is the reverse, the ‘integer to ascii’ function.

You would use atoi to convert a string, say, “23557” to the actual integer 23557.

Similarly, you would use itoa to convert an integer, say 44711, to the equivalent string “44711”.

Very handy.

Now, if you’ve written a lot of code using Microsoft Visual C++ (which is where I first started when I was learning C and C++), you may not be aware of the fact that atoi is part of the ANSI standard, whereas itoa is not. The MSVC compiler supports itoa, so if you are coding on this platform – particularly if you are learning on this platform – then it appears that atoi and itoa are a complementary┬ápair that would be available everywhere. Not so!

Read more

Getting Started With C Programming – Hello World Tutorial

If you’ve always wanted to dabble in C, but never quite gotten around to it, have a read through this and give it a go.

It is much easier than you might think (easier now, in fact, than it ever has been), to write your first C program, and there is something so deliciously inviting about the language that once you get started you’ll soon be solving world issues with your code.

To follow along with me:

You will need

  1. A computer running a Linux variant (I use Fedora)
  2. A compiler
  3. This walkthrough

Read more

How To Compile a 32-bit Executable on 64-bit Fedora 19

You know how sometimes you just have to compile and run a 32 bit program on a 64 bit machine, and it’s really annoying that it doesn’t seem to work?

Yeah, me too.

Turns out it’s actually pretty straightforward on Fedora 19.

First of all, you need to use the -m32 build flag. Below I’m using it to compile my program ‘pointers’:

gcc -m32 pointers.c -o pointers

You may run into the following error:

/usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory
# include <gnu/stubs-32.h>
compilation terminated.

To fix this you need to install the 32 bit glibc-devel package. You can do this by running:

yum install glibc-devel.i686

Next, you might see this error:

/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.8.2/ when searching for -lgcc_s
/usr/bin/ld: cannot find -lgcc_s
collect2: error: ld returned 1 exit status

Which means you need to install the 32 bit standard C++ library package. You can do this by running:

yum install libstdc++-devel.i686

Then you can quite happily compile your executable with the -m32 flag, as above:

gcc -m32 pointers.c -o pointers

And, as if by magic, you get a 32 bit exe that runs on your 64 bit machine.

You can use the file command to admire what you’ve made:

[faye@localhost src]$ file pointers
pointers: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), 
for GNU/Linux 2.6.32, BuildID[sha1]=0x39958fed2f5c099ad97fd7512e780066acfb1231, not stripped