tomclegg.net


Diary
Examples
Hire Tom
Mostly Mozart
Patches
School
Scrapbook
Software
    allaboutme
  >byteswap<
    checksocks
    djbdns-ipv6
    dsprec
    fresnel
    fresnel
    logger
    mail-transport-agent
    maildirpop3d
    mp3cat
    qmail-bmf-wildcard
    rawrms
    stationbreak
Telephones




colocation
comments
davidireland
edsgranola
faq
funsites
goodlooking
goodmovies
google-earth-saucy-amd64
houserules
liberating
resume
resume2
scratch
shopping
snacks
todo
university
warisbogus

Byteswap
Posted June 25, 2004

Read words from standard input, swap byte order, write to standard output.

/* byteswap.c */
/* tom clegg */
/* public domain */
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

int main()
{
  long bytesread, bufused, i;
  unsigned char buf[1048576], x;

  bufused=0;
  while(0 < (bytesread=read(STDIN_FILENO, buf+bufused, sizeof(buf)-bufused))) {
    bytesread+=bufused;
    for (i=0; i<(bytesread&~1); i+=2) {
      buf[i] ^= buf[i+1];
      buf[i+1] ^= buf[i];
      buf[i] ^= buf[i+1];
    }
    write(STDOUT_FILENO, buf, bytesread&~1);
    if (bytesread&1) {
      bufused=1;
      buf[0]=buf[bytesread-1];
    } else
      bufused=0;
  }
  if(bufused)
    write(STDOUT_FILENO, buf, bufused);
  exit(0);
}