nf – A Simple Number Format Utility
One of the projects I’m working on requires me to switch between decimal and hexadecimal formats for values that I’m dealing with. I found myself using Google quite a bit to convert between number formats, but after a day or two of constantly opening my web browser to do this, it was getting to be a pain.
I decided to write a quick utility that I could use from the command line to view a number in all three formats. Hence, I present you with nf, short for ‘number format’:
int main( int argc, char* argv[] ) {
if( argc != 2 ) {
printf( "usage: %s <number>\n", argv[0] );
exit( 0 );
}
long int num = strtol( argv[1], 0x0, 0 );
printf( "DEC: %ld\nOCT: %lo\nHEX: %lX\n", num, num, num );
}
Just compile it with your favorite C compiler, toss it in /usr/local/bin (or any other directory of your choice in your PATH), and you’re good to go. It generates output like the following:
$ nf 42 DEC: 42 OCT: 52 HEX: 2A
The argument passed to nf can be in decimal, octal, or hex format; strtol() automatically determines which format you’re using. Decimal numbers begin with any digit 1-9, octal numbers begin with a 0, and hex numbers begin with 0x. Thus, the utility can be used to convert between all three formats.