asprintf
Over a year ago, I created a new function called sprintfAlloc that was like sprintf, except it printed into and returned a newly-allocated chunk of memory. For more details, check out the original post.
In my travels since then, I’ve run across another function, in the GNU C library, that does the same thing. This function is called asprintf, and has this signature:
int asprintf(char** ret, const char* format, ...);
For more information, check out the manual page.
blackletter-gothic coding geek hardware humor link wikipedia
by Layne
leave a comment
Blinkenlights
Blinkenlights is a hacker’s neologism for diagnostic lights on old mainframe computers and modern network hardware. The Jargon File gives the following etymology:
“This term derives from the last word of the famous blackletter-Gothic sign in mangled mock German that once graced about half the computer rooms in the English-speaking world.”
Blinkenlights – Wikipedia, the free encyclopedia
Text Form:
ACHTUNG! ALLES TURISTEN UND NONTEKNISCHEN LOOKENPEEPERS! DAS KOMPUTERMASCHINE IST NICHT FÜR DER GEFINGERPOKEN UND MITTENGRABEN! ODERWISE IST EASY TO SCHNAPPEN DER SPRINGENWERK, BLOWENFUSEN UND POPPENCORKEN MIT SPITZENSPARKSEN. IST NICHT FÜR GEWERKEN BEI DUMMKOPFEN. DER RUBBERNECKEN SIGHTSEEREN KEEPEN DAS COTTONPICKEN HÄNDER IN DAS POCKETS MUSS. ZO RELAXEN UND WATSCHEN DER BLINKENLICHTEN.
Blackletter-Gothic Rendered Form:
16-bit CRC-CCITT
The proper way to implement the CCITT CRC-16 checksum. Apparently many websites and tutorials are giving bad information and source code, so beware!
Robots Unite!
I saw this in a robots.txt file on a friend’s webserver:
# robots unite!
# please contact robots (at) jtolds (dot) com to enlist in the grand robot army.
# to be eligible you must pass a simplified turing test.
code coding computer-science geek geometry link mathematics original-content
by Layne
leave a comment
Distance Calculation using Latitude and Longitude
Because of the near-spherical shape of the Earth, technically an oblate spheroid, calculating an accurate distance between two points requires the use of spherical geometry and trigonometric math functions. However, you can calculate an approximate distance using much simpler math functions. For many applications the approximate distance calculations provide sufficient accuracy with much less computational complexity.
Distance Calculation using Latitude and Longitude
There are a number of different approximations to calculate the surface-distance on a sphere using latitude & longitude coordinates. For my personal edification, I’m going to do some sample calculations for the distance between New York City (40°43′N 74°00′W) and Los Angeles (34°03′N 118°15′W), as well as between Eau Claire, WI (44°48′53″N 91°29′34″W) and Minneapolis, MN (44°58′48.36″N 93°15′6.72″W).
I’m going to convert to strictly degrees right away to ease the calculations:
Eau Claire: 44.8147°N 91.4928°W
Minneapolis: 44.8833°N 93.2519°W
New York City: 40.7167°N 74°W
Los Angeles: 34.05°N 118.25°W
-
Basic Math: This method only uses addition, subtraction, and multiplication, and is a basic application of Pythagoras’ theorem, a^2 + b^2 = c^2.
Approximate distance in miles = sqrt(x * x + y * y)
where y = 69.1 * (lat2 - lat1)
and x = 53.0 * (lon2 - lon1)
By this method, the distance from Eau Claire to Minneapolis is 93.3527 miles, and the distance from NYC to LA is 2390.0656 miles. -
Basic Math plus Trig: Add in a cosine term, and things get better:
Approximate distance in miles = sqrt(x * x + y * y)
where y = 69.1 * (lat2 - lat1)
and x = 69.1 * (lon2 - lon1) * cos(lat1/57.3)
By this method, the distance from Eau Claire to Minneapolis is 86.2617 miles, and the distance from NYC to LA is 2575.0506. -
Great Circle Distance Formula: Using real spherical coordinates, this formula will give us the ‘perfect’ answer, to the accuracy of our input numbers:
Distance in miles = 3963.0 * arctan[sqrt(1-x^2)/x]
where
x = [sin(lat1/57.2958) * sin(lat2/57.2958)] + [cos(lat1/57.2958) * cos(lat2/57.2958) * cos(lon2/57.2958 - lon1/57.2958)]
By this method, the distance from Eau Claire to Minneapolis is 86.3905 miles, and the distance from NYC to LA is 2448.8690 miles.
Source Webpage: Distance Calculation using Latitude and Longitude
See Also:
code electrical-engineering electronics engineering geek microcontroller plug
by Layne
leave a comment
Plug: LED Bargraph
Abstract: This project is a precursor to my forthcoming accelerometer project. I wanted to be able to visualize an analog signal using LED bargraph displays. In this project I explore capturing and smoothing an analog input signal, pseudo-multiplexing of output, and using a transistor as a switch to switch more current than the microcontroller can handle.
General Description: The device I am using for this project, the PIC18F452, has an integrated Analog to Digital (ADC) converter. This allows the microcontroller to measure an analog signal between 0 and 5 volts, and convert it to a 10-bit binary number. I am using a variable resistor, also known as a potentiometer, to easily create an analog voltage at pin 1 (AN0). In my program, I measure this value 128 times in a row, and then calculate the average of these 128 samples. The average voltage is scaled to be an integer between -10 and 10, inclusive on both ends. An appropriate number of LED segments are lit to represent the value.
Get your (tons|tonnes) straight!
FYI:
Metric Ton, also spelled Tonne, is equal to 1000 kilograms, or 2204.6226 pounds. Technically it should be called a “megagram”, but nobody uses that unit.
Short Ton, equal to 2000 pounds, is the ‘normal’ ton in the American system.
Long Ton, equal to 2240 pounds, is the ‘normal’ ton in the old Imperial system. Still used to measure the displacement of ships (even in America.)
Does Visual Studio Rot the Mind?
Does Visual Studio Rot the Mind?
It’s not that IntelliSense is teaching us to program like a machine; it’s just that IntelliSense would be much happier if we did.
And I think it’s making us dumber. Instead of finding out exactly the method I need, or instead of trying to remember an elusive property name, I find myself scrolling through the possibilities that IntelliSense provides, looking for a familiar name, or at least something that seems like it might do the job.
I don’t need to remember anything any more. IntelliSense will remember it for me. Besides, I justify to myself, I may not want those 60,000 methods and properties cluttering up my mind. My overall mental health will undoubtedly be better without them, but at the same time I’m prevented from ever achieving a fluid coding style because the coding is not coming entirely from my head. My coding has become a constant dialog with IntelliSense.
So I don’t think IntelliSense is helping us become better programmers. The real objective is for us to become faster programmers, which also means that it’s cheapening our labor.
assembly code coding foiled-again geek hack hacking idiotic internet link original-content webdesign
by Layne
leave a comment
Well this is a new idea…or maybe not.
I was redirected to a humorous (and by humorous, I mean pathetic) website attempting to infect me with a virus (or so I thought, see below), under the false premise that I had just received an eCard from “a relative”. I took a look at the source code, and an realized that most of the website was seemingly binary data in a javascript function. I dug a bit deeper, and found that they had written a little XOR routine in javascript to transform their ‘binary’ data into actual html, and were using the function to hide the true intent from the casual observer. Here is the function, and a small sample of the ‘binary’ data they included:
Phase One:
<Script Language='JavaScript'>
function xor_str(plain_str, xor_key)
{
var xored_str = "";
for (var i = 0 ; i < plain_str.length; ++i)
xored_str += String.fromCharCode(xor_key ^ plain_str.charCodeAt(i));
return xored_str;
}
var plain_str = "\xbd\x97\x97\x97\x97 ...(There was a lot of stuff here).... \xa3\xbd";
var xored_str = xor_str(plain_str, 157);
document.write(xored_str);
</script>
Phase Two:
I have translated this mess, and come up with the following much-less cryptic code:
<HTML>
<HEAD>
<SCRIPT>
var s=unescape("% u4141%u 4141%u 4141%u 4141%u 4141%u 4141%u 4141%u 4141");
//There were no spaces in the original string above,
// I removed them so they wouldn't be changed.
// The same thing applies below...
do
{
s+=s;
}
while (s.length<0x0900000);
s += unescape("%u 54EB%u 758B ...lots of data was here... %u 702E%u 7068");
</SCRIPT>
</HEAD>
<BODY>
<EMBED SRC="-------(lots more hyphens...)-----AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLAAA (char 0x05)NNNNOOOOAAA (char 0x05)QQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZ 0000111122223333444455556666777788889999.wmv"></EMBED>
</BODY>
</HTML>
Breakthrough:
Now, at this point, while trying to find out how to escape those pesky "% u" encodings, I stumbled upon a number of 'cracker' websites talking about a remote overflow in the Windows Media Player browser plugin. Turns out that this is a 'classic' heap spraying (s stands for spray) technique designed to exploit the buffer overflow. The character 0x41 is the letter 'A', and is also a NOP in windows' shellcode. The code generates an incredible number (16 MB worth) of NOP instructions, presumably enough to get past the runtime structures in the plugin's memory. After this massive dump of NOP's, the actual dangerous code is sent, which is apparently a standard Win32 "add administrator" payload from the website Metasploit, which creates a new local administrator with the username 'wmp0wn3d' and password 'password'.
So it turns out that it wasn't just a lame virus install attempt, but also an attempt to exploit a browser plugin security hole. Hurrah for microsoft!
Further Reading:
- http://www.babilonics.com/node/1348
- http://www.governmentsecurity.org/forum/index.php?showtopic=19332
- http://www.webservertalk.com/archive89-2006-11-1708485.html
sprintf + malloc ?= sprintfAlloc
When programming in C, I often want to create a string using other strings and string constants. Most times I want to just print it out, and printf works just fine. Other times, I want to store the result into a string, using sprintf. However, it’s often hard to know how much memory to allocate, especially if I’m using variable-length parameters in the call to sprintf. I learned today that you can use snprintf / vsnprintf in a tricky way to determine how much space to allocate.
The secret lies in passing a size parameter of 0 (zero). This causes the function call to not write anything to memory, and simply return the number of bytes that would have been written. I have written a function that behaves just like the printf family of functions, but returns a freshly-allocated chunk of memory. The caller assumes responsibility for free-ing the returned memory.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
char* sprintfAlloc(char* format, ...)
{
va_list v1;
va_start(v1, format);
int numBytes = sizeof('\0') + vsnprintf(NULL, 0, format, v1);
va_end(v1);
char* str = (char*) malloc(sizeof(char) * numBytes);
if (str == NULL)
{
return NULL;
}
va_start(v1, format);
vsprintf(str, format, v1);
va_end(v1);
return (str);
}
int main()
{
char* string = sprintfAlloc("%s = %d", "matthew", 42);
printf("result: '%s'\n", string);
free(string);
exit(0);
}

