views:

4147

answers:

46

As programmers, we've all put together a really cool program or pieced together some hardware in an interesting way to solve a problem. Today I was thinking about those hacks and how some of them are deprecated by modern technology (for example, you no longer need to hack your Tivo to add a network port). In the software world, we take things like drag-and-drop on a web page for granted now, but not too long ago that was a pretty exciting hack as well.

One of the neatest hardware hacks I've seen was done by a former coworker at a telecom company years ago. He had a small portable television in his office and he would watch it all day long while working. To get away with it, he wired a switch to the on/off that was activated via his foot under his desk.

What's the coolest hardware or software hack you've personally seen or done? What hack are you working on right now?

+8  A: 

Its such a trivial thing, but when I first saw this code (by a fellow developer of mine) I was shocked because it is something I would have never thought of (comments added by me):

cglobal x264_sub8x8_dct_sse2, 3,3  ;3,3 means 3 arguments and 3 registers used
.skip_prologue:
    call .8x4
    add  r0, 64                    ;increment pointers
    add  r1, 4*FENC_STRIDE
    add  r2, 4*FDEC_STRIDE
.8x4:
    SUB_DCT4 2x4x4W                ;this macro does the actual transform
    movhps [r0+32], m0             ;store second half of output data
    movhps [r0+40], m1             ;the rest is done in the macro
    movhps [r0+48], m2
    movhps [r0+56], m3
    ret

It does an 8x8 block of 4 transforms by doing sets of 8x4 at a time. But it doesn't paste the code twice (that would waste code size), nor does it have an 8x4 function and call it twice. Nor does it have a loop either. Instead, it calls the "function" and then increments the pointers, and then "falls" right into it and does it again.

It gets the best of both worlds: no function calling overhead beyond the original (since the pointers r0, r1, and r2 aren't incremented in SUB_DCT4) and no code duplication, and no loop overhead.

Dark Shikari
+3  A: 

Seeing my former workmate rewriting a playstation one 3d engine within three weeks from scratch in assembler. The old one was to slow and we didn't had the time to change the graphic assets anymore. He started that rewrite two month before deadline.

It was the same guy (and some other dudes as well - it was an act of teamwork) who did an amazing job stuffing 10 minutes of graphics and sound into a 64kb executable.

http://pouet.net/prod.php?which=1221

Nils Pipenbrinck
+8  A: 

The Fast Inverse Square Root-- a bizarre little routine that somehow manages to compute the inverse square root of something, but you'd never guess that from looking at it.

http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/

Asmor
I read the article...now my head hurts!
EJB
+1  A: 

int round(double d) { return (int)(d + .5) }

So simple... :)

Aaron
+1  A: 

@[Aaron] only works for positive numbers...

mrlinx
+1  A: 

The first time I had to try to understand and modify a piece of code written in a functional style. I spent an hour trying to understand where anything happened, then found that all of the work was done in a line that looked something like this:

for my $row (@data) {
  push @formatted, join ",", map $format[$_]->($data->[$_]), 0..$#$data;
}

I tracked down the author and exclaimed, "Why didn't you comment that???" His response was, "What comment would have helped?" I tried to think of one, and failed.

That code taught me a technique that I have found very useful to this day. However I have learned that it is a technique that should be used often or never, but nowhere in between. Because, really, no comment will help. Either you understand that there is a line there, what it does, and that you don't need to worry about it, or else you won't understand that code.

The same programmer routinely did other impressive things. For example at a previous job he had modified the C library so that when a C program dumped core it didn't just dump core. Instead it would create a coredump, then send an email to the development team with a stack backtrace and the coredump attached. This allowed them to notice and fix bugs in cron jobs that had problems.

Impressive code is not necessarily a good thing. I don't claim to understand what the line does, but I'd wager that there's a more clear, if more verbose, way of doing it.
Asmor
You'd wager wrong then. That line let's you move logic from where you do work to the setup of the format functions. If you know the technique, maintenance is easy. If you don't know it, a rewrite won't help.
+1  A: 

Casting a string with .ToString() is always a WTF I find.

Slace
+2  A: 

It's an oldie, but for me it was Duff's device:

http://en.wikipedia.org/wiki/Duff's_device

(for some reason I can't get markdown to show that URL as a link)


strcpy(to, from, count)
char *to, *from;
int count;
{
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}
Michael Burr
To post a link, put pointy brackets around it <like this>. To use different text to the URL itself, put your text in square brackets, and then the url in parentheses beside it [like this](http://www.google.com)
nickf
I tried all the different variations for links shown in the markdown help - it shows in the preview as a link, but not in the answer itself. I've done plenty of links elsewhere. I dunno what's going on here...
Michael Burr
+11  A: 

Duff's Device. Does that count? :)

Gabriel Isenberg
Dunno. What is it?
Treb
@Treb http://en.wikipedia.org/wiki/Duffs_device
Kyle Cronin
+50  A: 

The quake3 inverse square root and the MIT Magic/More Magic switch usually make these lists.

Tom Ritter
All of the MIT hacks are cool, but I'd like to know what SO readers have done or personally seen.
Robert S.
That Newton's approximation hack is badass.
Bob King
And just for kicks, an awesome story about trying to find who wrote that inverse square root function : http://www.beyond3d.com/content/articles/8/
m_oLogin
We still don't know who came up with it
BlueRaja - Danny Pflughoeft
+15  A: 

I made a divide-by-eight counter out of pneumatic valves in college in order to get exempted from the remainder of the pneumatics course.

Diodeus
+1 for cleverly getting out of what I assume was a boring class.
MatrixFrog
+5  A: 

I once hacked together a simple dos-style commandline for the psion 3a during a university lecture. It could only do basic directory listing, browsing, copy & move, but it looked the part - full screen a small font.

Oh, and I programmed pong for the 68008 with pots for input and an oscilloscope for output. Not that hard using a dev board, but there was something cool about playing it on an osc.

Draemon
+10  A: 

Duffs Device, for the above question.

The Story of Mel. Hardcore hack.

Paul Nathan
You're probably thinking of the Story of Mel, a programmer at Royal Bee.
Paul Tomblin
The Story of Mel: http://www.catb.org/jargon/html/story-of-mel.html
Graeme Perrow
Yes! Awesome! Thank you!
Paul Nathan
+2  A: 

Back in high-school I was really proud of writing a 3d graphing program on my ti-83 because my parents wouldn't buy me an 89.

Wyatt
In high-school, I had a TI-85, and figured out how to get near real-time key presses. Something my friends couldn't do, so my sucky game was more responsive than the games my friends made (which were admittedly better in other respects).
torial
lol, That's cool bro. You'll have to share ;).
SD
+6  A: 

A friend of mine was replacing the motherboard in his Dell with newer, faster, OEM motherboard. However, he couldn't get the power button, and other front-panel stuff, to work -- the connectors were different sizes, with different pin layouts. I took a bunch of spare jumpers and spare wires, and connected the proper pins one by one. No soldering needed :)

Code-wise, I'm constantly being impressed. I always thought there was no elegant way of determining whether a forked child successfully execed, but there actually is.

child:

execvp(argv[0], argv);
errval = errno;
write(data->fd, &errval, sizeof(errval));

parent:

socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
flag = fcntl(fds[1], F_GETFD) | FD_CLOEXEC;
fcntl(fds[1], F_SETFD, flag);
pid = clone(child, NULL, SIGCHLD, NULL);
if(pid < 0){
        ...
}
close(fds[1]);
/* Read the errno value from the child, if the exec failed, or get 0 if
 * the exec succeeded because the pipe fd was set as close-on-exec.
 */
n = read(fds[0], &ret, sizeof(ret));
if (n < 0) {
        ...
} else if(n != 0){
        /* exec failed */
} else {
        /* exec succeeded */
}
ephemient
+37  A: 

Well, it's not the coolest, but it's definitely funny (to programmers).

We built an ad-hoc query builder for a resume database project. There were some ajaxy parts to it and the basic idea was that if you changed anything on the page, the search automatically re-ran itself. (It was triggered by the onBlur event of all the UI widgets)

So we had no real use for a "Search" or "Run Query" button. This confused the users to no end. So we added a search button which did nothing. It just sat there.

It worked because every time you clicked the search button, the onBlur event from the field you were just on would fire.

This made our user base very happy. Simple things.

Zachary Yates
That's a good one!
Robert S.
Simple things - yeah, shure!
Treb
To be honest, I would be confused too if I had to press tab (or click out of an editbox) instead of enter to do things like activate a search.
J c
That's why we changed it! ;) (Pressing enter did work though)
Zachary Yates
especially if you just wanted to refresh the current search
1800 INFORMATION
Lesson: Programmers can be too smart for their user base.
Cheeso
+4  A: 

A couple years ago I was developing a web interface and using some brand-new JS libs for AJAX funtionality. The lib only eval'd JS that was in the html doc header, but there was too much data being returned to fit in the header. What to do?

Some poking around revealed that the JS in the header had access to the body of the html doc, so I wrote a generic 'eval the body' function that was returned in the header. Very useful at the time, especially b/c a different JS lib we were evaluating only eval'd JS from the body, so this was compatible for both JS libs and avoided any size constraints from the header!

Yes, simple, but I felt quite awesome for a whole month after figuring this out :)

jpeacock
+8  A: 

Steve Wozniak's disk controller.

Martin Cote
+7  A: 

Tesla's device set the record for man-made lightning (42 meters or 130 feet) and all the lights in Colorado Springs had gone out.

Serhat Özgel
+5  A: 

I would tell you, but they may want my high school diploma back if I admitted to it ;)

tloach
Lame. The interwebs is secure. Please do tell.
Baddie
+21  A: 

While working on the reverse-engineering effort of the iPhone, I found a vulnerability in the baseband (chip that handles the telephony and the carrier lock) that would allow you to write zeros arbitrarily. Although this seemed useless at first, it quickly became apparent that this could do far more than I had initially thought. With the way ARM works, certain jumps could be made nullified by writing a single zero in the target, causing the execution path to always continue forward. This enabled a software unlock, but was quickly replaced by a more robust hack that allowed you to reflash the baseband entirely.

Still damn proud of that hack, regardless of its uselessness now.

Cody Brocious
I dont think you know how much such hack helped people like me living in countries where we could get iPhones at first :)
mslot
+40  A: 

I recall this hack as being written by Bob Smith, who did the old DOS-era memory manager called 386MAX (or "386 to the Max"). It wasn't part of the product, it was a little utility program he whipped up and posted somewhere. However, on the web the only reference to this technique I can find is a DDJ Undocumented Corner column from November 1996 by Robert Collins.

The Problem

Prior to Intel introducing the CPUID instruction, it was difficult to check the exact type and revision levels of the CPU on your system. It turns out that in most versions of the 386 and later, there actually was a CPU ID, but it was only visible at one specific time: right after the processor was reset in the EDX register. (It was assumed that the computer's BIOS would be the only software legitimately interested in this).

Problem: how can a normal program retrieve this register value if we are not the BIOS?

Background Material

This hack relied on six distinct peculiarities of IBM PC compatible computers. They were as follows:

  1. Starting with the IBM AT and later, there is a way to independently disable the A20 address line on the bus.
  2. Most computers do not have RAM installed in very high memory addresses just below the BIOS ROM.
  3. Most IBM PC bus computers return 0xFF when you read a memory location that has no memory installed there.
  4. 0xFF 0xFF 0xFF etc is an illegal opcode on Intel CPUs.
  5. If you install an exception handler in memory, it will survive a soft reboot on most CPUs of this era (386 through 486).
  6. Upon soft or hard reset, Intel processors jump to an address which is at the top of addressable memory, minus 16 bytes, which is why the BIOS ROM is placed there.

The program combined knowledge of all these pieces of trivia to achieve the goal.

The Hack

The result was a DOS command line program, that did the following:

  • Installed an illegal opcode exception handler
  • Turned off the A20 address line on the bus
  • Soft-rebooted the CPU (I think this was through a BIOS call)

When the soft reboot occurred, the processor would try to jump to the top of memory minus 16 bytes, which is where the ROM startup code is located. However, since A20 was off, it would actually jump to top of memory minus 16 bytes minus one megabyte. On most PCs there is no RAM there. So it would fetch a series of 0xFF bytes from this non-existent RAM, and try to execute it. This would create an illegal opcode exception.

His exception handler would then pluck out the value of EDX (the CPUID) and stash it somewhere he could find it. It would then clean up the mess (turn A20 back on, flip back from protected mode to real mode for DOS) and return control to the original code.

When it worked, it was genius to behold. Voila, here was a simple command-line DOS program that would give you the CPUID value.

Of course, there were inevitably PCs out there which were "not quite compatible" which would crash horribly when you ran this. Ah well.

Tim Farley
I worked on the All Computers "All Charge 386", which was a little board that allowed you to plug a 386SX into a 286 socket so OS2 + Windows users could use extended memory. I was working on a new unit with its own CPU clock and ram on-board too.
Diodeus
+4  A: 

I wrote a simple Windows batch file to let me quickly play tracks matching some pattern from my music library (on f: drive) on a painfully slow machine (opening iTunes takes about 3 minutes on this machine!). It supports regular expressions via the findstr command and uses mplayer to play the tracks. All I have to do is press Windows+R and type:

play u2

or:

play "neighbo.+rhood"

or:

play "blink[0-9][0-9][0-9]"

The batch file is like this, in play.bat.

cd /d f:
findstr /I /R %1 dirlist.txt > playlist.txt
mplayer -playlist playlist.txt

Both mplayer and play.bat should be added to your path.

Liam
+7  A: 

We were compromised at the small company I worked at by some supposedly Russian hackers. Myself and a few other developers wanted to see how, and so I pulled down the most elegant PHP script I have ever seen down from our server, and promptly deleted it from our live machine.

It was a trojan horse called c99shell which did so much with so little that it was both horrible and beautiful at the same time. The thing had an embedded GUI with images using base64 to output them from the PHP so everything was self contained. The feature list was sick! This thing could start shells, scan for connection strings, lock itself down and a number of other useful things for an attacker.

It was beautiful.

Everyone in the office thought I was nuts, but really, truly this code had quite a bit of thought put into it. They kept the file size small so as to sneak past those pesky upload limits and even had a base64 encoded email notification which collected all the information for the attacker.

Abyss Knight
If you live in a country where you have a lot of time on your hands, and you're real smart, and nobody's around to pay you do burn your creativity on them, these kinds of things tend to manifest.I keep telling people: You never hear of a virus that fails to install correctly.Maybe those guys should be writing all the software, they know what they're doing.
stu
+4  A: 

I wrote an assembler for a small Virtual Machine (UDVM) with Excel and Visual Basic. You write your assembly code in the Excel cells and your memory layout in the other worksheet, and then at the bottom the machine code binary strings will be calculated. Imagine the dread of hand assemblying every time you change your assembly code.

yogman
I had a friend who wrote an assembly interpreter using windows batch files; I'll post the link later if I can find it
BlueRaja - Danny Pflughoeft
+9  A: 

This summer I wrote a game that I call SatelliteRush. It's a Breakout game for mobile phones with Java and GPS. It can be played in two modes: "boring mode" and "satellite mode". In boring mode, you use buttons to move the paddle, just as usual, but in satellite mode it uses the phone's GPS receiver. You run back and forth, and the paddle moves with you.

I've only tested it on a Sony-Ericsson W760i, and it works reasonably well, given that GPS position updates are rather slow and inexact.

So far I have made a "technical test version" of this game, so it's is not very good-looking or easy to use. But if you have a GPS phone with Java you can download it here: http://www.lysator.liu.se/~padrone/temporary/SatelliteRushTest/

Thomas Padron-McCarthy
...someone is going to get hit by a bus whilst furiously playing pong.
Grank
+6  A: 

Back in the days of DOS, I wrote a scripting program to demonstrate my company's software. This scripting program would start the application and then pop up windows on top of the application, describe some of its features using animated type, then close the window, feed keystrokes to the application, wait for the application to display the proper screen, and then pop up more windows. It had its own scripting language and even a script editor so I could interrupt the script, edit it, and then resume running it. The best part is that it ran on top of an unmodified version of our application.

The whole demo application was written in C and assembly language. It hooked timer and keyboard interrupts in order to interact with the application. I wrote everything, including the windowing library.

Kluge
+1  A: 

There is the switch nested inside loop for loop unwinding known as the Duff device

dsend(to, from, count)
char *to, *from;
int count;
{
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}

Its not THAT powerful however it is a nice abuse of the C syntax

Eric
+25  A: 

This wasn't a hack I did, but rather someone I worked for a long time ago told me about it (he actually did the hack).

It seems he worked for someone who was blind and who needed a way to read text files. So he figured out how to translate text files to braille and print them out using various characters such as . and :

The printers at the time were impact printers, so when a character was printed, the printing mechanism struck the paper hard enough to leave an impression that could be felt. Since the impression formed on the back of the paper, he had to print an inverted-backwards braille so that when the paper was turned around it was correct.

Of course, the act of reading eliminated the depressions so it was a read-once mechanism, but I always thought that was a pretty cool hack.

Ferruccio
this was cool for three reasons:- text to braille- inverted-backwards braille- read-once.
Irwin
This message will self destruct in...now.
LeopardSkinPillBoxHat
+2  A: 

When looking at how to use TCP in 4D, I came across this variation of the Duff Device in the documentation:

$SentOK:=False  //A flag to indicate if we made it through all of the calls
Case of 
   : (SMTP_New ($smtp_id)!=0)
   : (SMTP_Host ($smtp_id;<>pref_Server)!=0)
   : (SMTP_From ($smtp_id;vFrom)!=0)
   : (SMTP_To ($smtp_id;vTo)!=0)
   : (SMTP_Subject ($smtp_id;vSubject)!=0)
   : (SMTP_Body ($smtp_id;vMessage)!=0)
   : (SMTP_Send ($smtp_id)!=0)
Else 
   $SentOK:=True  //message was composed and mailed successfully
End case 
If ($smtp_id!=0)  //If a Message Envelope was created we should clear it now
   $OK:=SMTP_Clear ($smtp_id)
End if

I looked at it and thought it was really clever (I still do). Unfortunately, it wasn't what I needed and I never got the chance to use it.

Alex Brault
+3  A: 

After several days of debugging a dial-up server that was experiencing an unacceptable number of dropped calls, I traced the problem to a home-grown authentication mechanism that depended on the text representation of the running getty's PID. The getty would generate an error and abort if its PID contained an even number followed by a 9, causing the call to drop and the getty to respawn with a new PID.

After the problem was identified, I was taken off the project and later discovered that the "fix" was to change the numeric-to-text conversion from

sprintf(strval, "%d", pid);

to

sprintf(strval, "%o", pid);

Rather than troubleshooting the authentication routine, someone chose to convert the PID to octal, making it impossible to contain a 9!

Adam Liss
+1  A: 

http://pida.co.uk/ A hack that would end the Vim/Emacs flame war! (!!11eleven)

Ali A
A: 

Simple one. One of my early mentors went off on summer vacation with his family. When he returned he immediatelly sat at the terminal and typed in a GMAP routine, compiled (clean) and pushed it out. I asked if I could help testing and he said it's ok he'd "sand tested" it. Huh? Apparently he was bored on the beach, so found a flat piece of sand, coded and checked it - "sand checked". Brilliant guy.

jsfain
+6  A: 

The coolest hack (and it's not really a hack in the true sense of the word, but it passes as well as some of the above answers) I've ever created was on my Apple //e.

There was one line in the reference manual that said $C010 was the 'any key down' flag.

Which it turned out was true. The high bit of the $C010 soft switch would tell you if a key was down or not despite the built-in key repeat hardware.

What they didn't tell you and everybody found out the hard way was that there was no reliably way to find out WHAT key was being pressed.

If you wrote a little assembly program... (pardon my mistakes, my 6502 assembly is a lot rusty)

  :1
  lda $C010
  cmp #$80
  bcc :1  ; branch if less than? I forget how to do that.
  lda $C000
  jsr $FDF0   ;output the accumulator value to the screen

So it would loop until you pressed a key and would output the key by loading from the $C000 keyboard read switch.

But if you ran that program, it wouldn't quite work right.

It would certainly print out something while you were holding a key down and nothing when you weren't but there was a little lag on the bus somewhere (I think, I'm not a hardware guy) so if you pressed 'f' you'd get lots of f's. But if you stopped, then pressed 'g', you'd get a bunch of 'f's before it switched to 'g'.

You could see evidence of this problem in the apple ][ version of Gauntlet, you'd move in one direction, and if you tried to move in a second direction, you'd move a little bit in your original direction until the you passed the lag.

It made no sense really, because reading $C000 was always 100% accurate, unless you pinged $C010 first.

I found this problem fascinating and after weeks of playing I finally came up with what I still think is the coolest program I've ever written.

The program itself made no sense, it did a few useless ORA's but for some reason it worked, and it yielded correct values from $C000 after querying $C010.

So cool was this, I wrote an article for nibble magazine, which they accepted but never published (either because they went out of business or because the article read like it was written by 15 year old, which it was) where I wrote a replacement keyboard input program and hooked it into the zero page location that everybody calls to get keyboard input and I was able to programmatically change the keyboard repeat delay and repeat rate, something that was otherwise impossible as it was wired into the hardware. Of course the Apple //e was on its way out at that point, but still to this day, my coolest hack.

Update 3/2/2010: Going through some old papers, I found a printout of my little assembly routine. I'm posting it here to see if anybody can figure out why it works, and so it will be forever enshrined in digital form somewhere...

$0300  AD 10 C0  LDA $C010  ; load accumulator with any-key-down flag
$0303  29 80     AND #$80   ; keep only high bit flag
$0305  0D 00 C0  ORA $C000  ; OR accumulate with keyboard soft switch
$0308  10 F9     BPL $0303  ; erm, I forget exactly which branch this is
$030A  09 80     ORA #$80   ; turn the high bit on 
$030C  20 ED FD  JSR $FDED  ; print char in accumulator
$030F  4C 00 30  JMP $0300  ; start again.

Makes no sense why this should work, but it does. Or did. 25 years ago.

stu
+4  A: 

Not done by me, of course, but I came across it recently and it looked cool:

Self-printing Game of Life in C#

"Conway’s Game of Life has fascinated computer scientists for decades. Even though its rules are ridiculously simple, Conway’s universe gives rise to a variety of gliders, spaceships, oscillators, glider guns, and other forms of “life”. Self-printing programs are similarly curious, and - rather surprisingly - have an important place in the theory of computation.

What happens when you combine the two? You are about to find out, but one thing is for sure: the geekiness factor should be pretty high.

I wrote a little C# program that contains a Game-of-Life grid. The program advances the game grid to the next generation and prints out a copy of itself, with the grid updated. You can take the output, compile it with a C# compiler, run it, and you’ll get the next generation of the game. You can iterate the process, or change the initial grid state manually. "

Follow the link above for source code.

Evgeny
+3  A: 

And a self-printing program ('quine') in C#, 149 characters long:

C# Quine

class P{static void Main(){var S=“class P{{static void Main(){{var S={1}{0}{1};System.Console.Write(S,S,’{1}’);}}}}”;System.Console.Write(S,S,‘”‘);}}
Evgeny
+7  A: 

I got an early Commodore 64 Computer, and needed to write assembly code for it.

Problem was, there was no Assembler Program for the C64 (either that, or I couldn't afford one).

So I wrote an assembler by looking up the 6502 opcodes in a book, and creating the program out of the raw bytes.

At some point it was able to take assembly code as its input, and assemble into a program.

A friend of mine had written a disassembler for his PET in BASIC. I used this program to disassemble my assembler, and was then able to use my assembler to assemble newer versions of itself.

Oh, the hoops we had to jump through in the old days :)

Alan
Real men wrote native code. The rest of us somehow managed to swipe an assembler from somewhere.Which brings up the pretty cool hack of the miniassembler in the integer basic roms of the early apple IIs. Actually all of the apple II roms were pretty amazing.
stu
+2  A: 

Making a scanner out of a printer head. Modern versions include Canon's, but this trick is actually really old.

Brian
+2  A: 

Not by me:

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
  int i;

  printf("((((");
  for(i=1;i!=argc;i++){
    if(     strcmp(argv[i], "^")==0) printf(")^(");
    else if(strcmp(argv[i], "*")==0) printf("))*((");
    else if(strcmp(argv[i], "/")==0) printf("))/((");
    else if(strcmp(argv[i], "+")==0) printf(")))+(((");
    else if(strcmp(argv[i], "-")==0) printf(")))-(((");
    else                             printf("%s", argv[i]);
  }
  printf("))))\n");
  return 0;
}
Brian
Whats this supposed to do??
Red Serpent
Operator precedence parser. See http://en.wikipedia.org/wiki/Operator-precedence_parser .
Brian
wow, I like this code, it seems to be simple but it made my apps hung for minutes(when ever I try to open my apps, they are stucking). Do U know what exactly this code do ? I alone can't figure out why my apps are being broken on running this code on my PC
Ninja Dude
+3  A: 

If you want a lot of C code with unbelievable hacks, try the International Obfuscated C Code Contest. They're generally not the sorts of things you want to be caught doing, but they're impressive anyway.

David Thornley
+1  A: 

A boot loader for a CPU that didn't support boot loaders.

The CPU is a derivitive of a member of a rockwell CPU family that runs the code it's given. The toolchain produces either RAM images ( which you can JTAG in and run for debugging) OR it producees ROM images.

There is a chaining bootloader. But it only chains. You've got to be running, and it only works for RAM.

Just in case I felt creative, The CPU has no JMP instruction. (I'm not kidding.) No RST instruction either.

So we needed to load a program from a file system and run it, and this CPU is very definitely embedded and doesn't want to do that.

The filesystem sat in Flash ROM and would only operate at the address it was written at. (It's not relocatable)

So I loaded the ROM with a boot loader that would boot load a boot loader into the bottom of RAM. The the CPU writes to a gate array, the that

1) asserts reset. 2) swaps the chip selects for RAM and ROM 3) releases the reset.

The CPU ends up running from RAM, ready to read code from the filesystem into RAM.

It actually works. I was "inspired" by the way the IBM PC-AT gets the 286 chip out of protected mode.

Tim Williscroft
+7  A: 

The Black Sunday Hack.

Brian
A: 

Years ago, I wrote a program to display text in big block letters, in order to put them in the header of my source files so I could print them multipage in very small font. I built a small table with the pixel information in a 5x5 square to print the characters. It only had capital letters and numbers. So pa would become...

####    #
#   #  # #
####  #   #
#     #####
#     #   #

some time later I found in the original IBM PC BIOS listing that came with the IBM PC Technigal Reference that it had a 8x8 character generator. So I found it and extracted it from a memory dump. So I was able to generate the complete character set, so I could use lowercase letters...

## ###   ####
 ##  ##     ##
 ##  ##  #####
 #####  ##  ##
 ##      ### ##
####
PA
A: 

Well, I was having trouble one time linking with the D3DX library in a DirectX application, so I manually called LoadLibrary and GetProcAddress to obtain entry points to the functions.

On a similar note, one other time, I was working on a game and needed a way to store logic in the levels. So I had the levels stored in DLL files that exported the necessary functions. The problem was that at that time, I didn't understand C++ name-mangling, so I thought "why are the names exported like [email protected]_4"? I ended up just opening the DLL files in Windows 98's QuickView to get the names and calling things like GetProcAddress("[email protected]_4")!

George Edison
+1  A: 

David Carlisle's TeX poem:

\let~\catcode~`76~`A13~`F1~`j00~`P2jdefA71F~`7113jdefPALLF
PA''FwPA;;FPAZZFLaLPA//71F71iPAHHFLPAzzFenPASSFthP;A$$FevP
[email protected]@FfPARR717273F737271P;ADDFRgniPAWW71FPATTFvePA**FstRsamP
AGGFRruoPAqq71.72.F717271PAYY7172F727171PA??Fi*LmPA&&71jfi
Fjfi71PAVVFjbigskipRPWGAUU71727374 75,76Fjpar71727375Djifx
:76jelse&[email protected]
RrhC?yLRurtKFeLPFovPgaTLtReRomL;PABB71 72,73:Fjif.73.jelse
B73:jfiXF71PU71 72,73:PWs;AMM71F71diPAJJFRdriPAQQFRsreLPAI
I71Fo71dPA!!FRgiePBt'[email protected] lTLqdrYmu.Q.,Ke;vz vzLqpip.Q.,tz;
;Lql.IrsZ.eap,qn.i. i.eLlMaesLdRcna,;!;h htLqm.MRasZ.ilk,%
s$;z zLqs'.ansZ.Ymi,/sx ;LYegseZRyal,@i;@ TLRlogdLrDsW,@;G
LcYlaDLbJsW,SWXJW ree @rzchLhzsW,;WERcesInW qt.'oL.Rtrul;e
doTsW,Wk;[email protected] aHAHHFndZPqpa.rtMRrgeLinZ.irLtYer.W,:jbye

run pdftex on this file and be amazed.

Patrick
A: 

I once used push buttons in FoxPro (windows) to generate bar chart in the very first program I wrote. That was really cool for me.

Vishal Seth