Dave's Brain

Browse - programming tips - reading and writing in network order

Date: 2008mar4
Language: C/C++

Q.  How do I read and write in "network" order?

A.  Network order (aka Big Endian) is the usual way
to write out number when its going to go over the net.
The low order stuff comes first.  Here are some routines
to read and write it.

#include <stdio.h>
typedef unsigned char DAVEKB_BYTE;
typedef unsigned short DAVEKB_WORD;
typedef unsigned long DAVEKB_DWORD;

//-------
// Two  helper functions

inline bool GetChunk(FILE *f, void *buf, const size_t size)
{
	return fread(buf, 1, size, f) == size;
}

inline bool PutChunk(FILE *f, const void *buf, const size_t size)
{
	return fwrite(buf, 1, size, f) == size;
}

//-------
// Get

bool GetWordNetwork(FILE *f, DAVEKB_WORD &w)
{
	DAVEKB_BYTE	buf[2];

	if (!GetChunk(f, buf, sizeof(buf))) return false;
	w = (buf[0]<<8) | buf[1];
	return true;
}

bool GetTripleByteNetwork(FILE *f, DAVEKB_DWORD &dw)
{
	DAVEKB_BYTE	buf[3];

	if (!GetChunk(f, buf, sizeof(buf))) return false;
	dw = (buf[0]<<16) | (buf[1]<<8) | buf[2];
	return true;
}

bool GetDoubleWordNetwork(FILE *f, DAVEKB_DWORD &dw)
{
	DAVEKB_BYTE	buf[4];

	if (!GetChunk(f, buf, sizeof(buf))) return false;
	dw = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
	return true;
}

//-------
// Put

bool PutWordNetwork(FILE *f, const DAVEKB_WORD w)
{
	DAVEKB_BYTE	buf[2];

	buf[0] = (DAVEKB_BYTE) (w >> 8);
	buf[1] = (DAVEKB_BYTE) (w & 0xff);
	return PutChunk(f, buf, sizeof(buf));
}

bool PutTripleWordNetwork(FILE *f, const DAVEKB_DWORD dw)
{
	DAVEKB_BYTE	buf[3];

	buf[0] = (DAVEKB_BYTE) (dw >> 16);
	buf[1] = (DAVEKB_BYTE) (dw >> 8) & 0xff;
	buf[2] = (DAVEKB_BYTE) (dw & 0xff);
	return PutChunk(f, buf, sizeof(buf));
}

bool PutDoubleWordNetwork(FILE *f, const DAVEKB_DWORD dw)
{
	DAVEKB_BYTE	buf[4];

	buf[0] = (DAVEKB_BYTE) (dw >> 24);
	buf[1] = (DAVEKB_BYTE) (dw >> 16) & 0xff;
	buf[2] = (DAVEKB_BYTE) (dw >> 8) & 0xff;
	buf[3] = (DAVEKB_BYTE) (dw & 0xff);
	return PutChunk(f, buf, sizeof(buf));
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.