Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-19 of 19 total

Java - int2bin

// Stampa la versione binaria di un numero

int numero = 15;
System.out.println(Integer.toBinaryString(numero));

Files Joiner/Unjoiner //Pascal class

This is just a snippet since I didn't added some units that can be replaced without major efforts:
- PathParser.pas: parses paths shortcuts (it's on my bigbold snippets, search on my tags)
- Stack.pas: implements a simple stack (it's on my bigbold snippets, search on my tags)
- ZlibEx.pas: used to compress/decompress the file contents (My ZlibEx is a modified version of this file: http://www.dellapasqua.com/delphizlib)
- MD5.pas: used to calculate the file hash and check consistency when unjoining files
- SysUtils2: Some idiot functions =b

I used this in a personalized installer that I've made in my first job =b


unit FileJoiner;

interface

uses
SysUtils, SysUtils2, Classes, MD5, ZlibEx, PathParser, Stack;

type
TOverwriteMode = ( omNo, omAskUser, omIfNewer, omIfOlder, omIfDiff );
TOverwriteAction = ( oaOverwriteAll, oaNoOverwriteAll, oaYes, oaNo );

TFileHeader = record
MD5Hash: TDigestStr;
ModificationDate: TDateTime;
Attributes: LongWord;
Overwrite: TOverwriteMode;
Size: Int64;
MustKeep: Boolean;
end;

TFileJoinerItem = class
public
Source, Destiny: string;
MustKeep, Recurse: Boolean;
Overwrite: TOverwriteMode;

constructor Create( const FromPath, ToPath: string; const OverwriteMode: TOverwriteMode = omIfNewer; const Recursive: Boolean = True; const MustKeepFile: Boolean = False ); overload;
function Assign( Item: TFileJoinerItem ): TFileJoinerItem;

procedure Save( const Stream: TStream );
procedure Load( const Stream: TStream );
end;

TCustomFileJoiner = class;

TFileJoinerFilesCallback = procedure( Sender: TCustomFileJoiner; Item: TFileJoinerItem ) of object;
TFileJoinerNotifyEvent = procedure( Sender: TCustomFileJoiner ) of object;
TFileJoinerFileExists = procedure( Sender: TCustomFileJoiner; var CanOverwrite: TOverwriteAction ) of object;

TJoinerStatus = ( jsIdle, jsJoining, jsUnjoining );

TCustomFileJoiner = class
private
FStream: TStream;
FCurFile, FTotalFiles: LongWord;
FCurSize, FTotalSize, FCurPosition, FCurWrittenBytes: Int64;
FCurFilename: string;
FCurFileInfo: TFileHeader;
FOnFileExists: TFileJoinerFileExists;
FOnWorkEnd, FOnWorkBegin, FOnWork, FOnProcessFile: TFileJoinerNotifyEvent;

procedure ProgressNotifier( Sender: TObject );

public
//properties
property CurFilename: string read FCurFilename;
property CurFileInfo: TFileHeader read FCurFileInfo;
property CurFilePosition: Int64 read FCurPosition;
property CurWrittenBytes: Int64 read FCurWrittenBytes;
property CurSize: Int64 read FCurSize;
property CurFile: LongWord read FCurFile;

property TotalSize: Int64 read FTotalSize;
property TotalFiles: LongWord read FTotalFiles;

//events
property OnWorkBegin: TFileJoinerNotifyEvent read FOnWorkBegin write FOnWorkBegin;
property OnWork: TFileJoinerNotifyEvent read FOnWork write FOnWork;
property OnWorkEnd: TFileJoinerNotifyEvent read FOnWorkEnd write FOnWorkEnd;
property OnProcessFile: TFileJoinerNotifyEvent read FOnProcessFile write FOnProcessFile;
property OnFileExists: TFileJoinerFileExists read FOnFileExists write FOnFileExists;
end;

TFileJoiner = class( TCustomFileJoiner )
private
FPaths: TList;

function GetItem(const Index: Integer): TFileJoinerItem;
function GetCount: Integer;
procedure StreamFile( Sender: TCustomFileJoiner; Item: TFileJoinerItem );
procedure Compress( Input: TStream );

public
constructor Create;
destructor Destroy; override;

procedure Join( const Filename: string ); overload;
procedure Join( const Stream: TStream ); overload;

procedure SaveList( const Filename: string ); overload;
procedure SaveList( Stream: TStream ); overload;
procedure LoadList( const Filename: string ); overload;
procedure LoadList( Stream: TStream ); overload;

procedure CountFiles;

function Add( const FromPath, ToPath: string; const OverwriteMode: TOverwriteMode = omIfNewer; const Recursive: Boolean = False; const MustKeep: Boolean = False ): Integer;
procedure Clear;
procedure Remove( const Index: Integer );
procedure ListFiles( const Callback: TFileJoinerFilesCallback );

property Count: Integer read GetCount;
property Items[ const Index: Integer ]: TFileJoinerItem read GetItem; default;
end;

TFileUnjoiner = class( TCustomFileJoiner )
private
FDataBegin: Int64;
procedure Decompress( Output: TStream );

public
procedure Assign( const Filename: string ); overload;
procedure Assign( Stream: TStream ); overload;
procedure UnJoin;
end;

implementation

{ TCustomFileJoiner }

procedure TCustomFileJoiner.ProgressNotifier(Sender: TObject);
begin
if Assigned( FOnWork ) then
with TStream( Sender ) do
begin
FCurWrittenBytes := Position - FCurPosition;
FCurPosition := Position;
FOnWork( Self );
end;
end;

{ TFileJoiner }

procedure TFileJoiner.Join( const Filename: string );
begin
FStream := TFileStream.Create( Filename, fmCreate );
try
Join( FStream );
finally
FStream.Free;
end;
end;

procedure TFileJoiner.Join( const Stream: TStream );
var
Pos: array[0..1] of Int64;
begin
FStream := Stream;
if Assigned( FOnWorkBegin ) then
FOnWorkBegin( Self );

FCurFile := 0;
FCurSize := 0;

//record position to get back later and reserve space on the file to record the "totals"
Pos[0] := FStream.Position;
FStream.Seek( SizeOf( FCurFile ) + SizeOf( FCurSize ), soCurrent );

//write files
ListFiles( StreamFile );

//write the totals and get back
Pos[1] := Stream.Position;
FStream.Position := Pos[0];
FStream.Write( FCurFile, SizeOf( FCurFile ) );
FStream.Write( FCurSize, SizeOf( FCurSize ) );
FStream.Position := Pos[1];

//job done
if Assigned( FOnWorkEnd ) then
FOnWorkEnd( Self );
end;

procedure TFileJoiner.StreamFile( Sender: TCustomFileJoiner; Item: TFileJoinerItem );
var
InputFile: TFileStream;
Pos: array[0..1] of Int64;
begin
try
Inc( FCurFile );
FCurPosition := 0;
FCurFilename := Item.Source;

FCurFileInfo.MD5Hash := FileMD5Digest( Item.Source );
FCurFileInfo.ModificationDate := FileDateToDateTime( FileAge( Item.Source ) );
FCurFileInfo.Attributes := FileGetAttr( Item.Source );
FCurFileInfo.Overwrite := Item.Overwrite;

InputFile := TFileStream.Create( Item.Source, fmOpenRead or fmShareDenyWrite );
try
FCurFileInfo.Size := InputFile.Size;
if Assigned( FOnProcessFile ) then
FOnProcessFile( Self );

Pos[0] := FStream.Position;
//reserve space for the file header and EOF position
FStream.Seek( SizeOf( FCurFileInfo ) + SizeOf( Pos[0] ), soCurrent );
StringWrite( FStream, Item.Destiny );

Compress( InputFile );

//update the header and get back
Pos[1] := FStream.Position;
FStream.Position := Pos[0];
FStream.Write( FCurFileInfo, SizeOf( FCurFileInfo ) );
FStream.Write( Pos[1], SizeOf( Pos[1] ) );
FStream.Position := Pos[1];

//update summary
Inc( FCurSize, FCurFileInfo.Size );
finally
InputFile.Free;
end;
except
on E: Exception do
raise EWriteError.CreateFmt( '%s.StreamFile: Error on joining: "%s" - %s', [ ClassName, FCurFilename, E.Message ] );
end;
end;

function TFileJoiner.Add(const FromPath, ToPath: string;
const OverwriteMode: TOverwriteMode; const Recursive: Boolean; const MustKeep: Boolean ): Integer;
begin
Result := FPaths.Add( TFileJoinerItem.Create( FromPath, ToPath, OverwriteMode, Recursive, MustKeep ) );
end;

procedure TFileJoiner.Clear;
var
I: Integer;
begin
for I := FPaths.Count - 1 downto 0 do
begin
TFileJoinerItem( FPaths[I] ).Free;
FPaths.Delete( I );
end;
end;

constructor TFileJoiner.Create;
begin
FPaths := TList.Create;
end;

destructor TFileJoiner.Destroy;
begin
Clear;
FPaths.Free;
inherited;
end;

procedure TFileJoiner.CountFiles;
type
PStackItem = ^TStackItem;
TStackItem = record
Data: PChar;
Searcher: TSearchRec;
end;

var
I: Integer;
Path, Filter: string;
Stack: TStack;
CurStack, X: PStackItem;
begin
FTotalFiles := 0;
FTotalSize := 0;

Stack := TStack.Create;
try
for I := 0 to FPaths.Count - 1 do
begin
Path := Self[I].Source;
if LastDelimiter( '*?', ExtractFileName( Path ) ) <> 0 then
begin
Filter := ExtractFileName( Path );
Path := ExtractFilePath( Path );
end
else if FileExists( Path ) then
else if DirectoryExists( Path ) then
begin
Filter := '*';
Path := AddSlash( Path );
end
else
raise Exception.CreateFmt( '%s.GetFilesSumary: "%s" não encontrado', [ ClassName, Path ] );

New( CurStack );
CurStack^.Data := CopyString( Path );
repeat
with CurStack^ do
begin
if FindFirst( Data + Filter, faDirectory, Searcher ) = 0 then
begin
repeat
Inc( FTotalFiles );
Inc( FTotalSize, Searcher.Size );
until FindNext( Searcher ) <> 0;
FindClose( Searcher );
end;

if Self[I].Recurse and ( FindFirst( Data + Filter, faArchive, Searcher ) = 0 ) then
begin
repeat
if Searcher.Name[1] <> '.' then
begin
New( X );
X^.Data := CopyString( AddSlash( Data + Searcher.Name ) );
Stack.Push( X );
end;
until FindNext( Searcher ) <> 0;
FindClose( Searcher );
end;
FreeMem( Data );
Dispose( CurStack );
CurStack := Stack.Pop;
end;
until CurStack = nil;
end;
finally
Stack.Free;
end;
end;

function TFileJoiner.GetItem(const Index: Integer): TFileJoinerItem;
begin
Result := FPaths.Items[ Index ];
end;

function TFileJoiner.GetCount: Integer;
begin
Result := FPaths.Count;
end;

procedure TFileJoiner.ListFiles( const Callback: TFileJoinerFilesCallback);
type
PStackItem = ^TStackItem;
TStackItem = record
Source, Destiny: PChar;
Searcher: TSearchRec;
end;

var
Stack: TStack;
Filter: string;
Current, X: PStackItem;
Data: TFileJoinerItem;
I: Integer;
begin
Stack := TStack.Create;
try
Data := TFileJoinerItem.Create;
try
for I := 0 to FPaths.Count - 1 do
begin
Data.Assign( Self[I] );
with Data do
begin
Destiny := AddSlash( Destiny );
if LastDelimiter( '*?', ExtractFileName( Source ) ) <> 0 then
begin
Filter := ExtractFileName( Source );
Source := ExtractFilePath( Source );
end
else if FileExists( Source ) then
begin
Destiny := Destiny + ExtractFileName( Data.Source );
Callback( Self, Data );
Continue;
end
else if DirectoryExists( Source ) then
begin
Filter := '*';
Destiny := AddSlash( Destiny + ExtractFileName( RemoveSlash( Source ) ) );
Source := AddSlash( Source );
end
else
raise Exception.CreateFmt( '%s.ListFiles: "%s" não encontrado', [ ClassName, Source ] );
end;

New( Current );
with Current^ do
begin
Source := CopyString( Data.Source );
Destiny := CopyString( Data.Destiny );
end;

repeat
with Current^ do
begin
if FindFirst( Source + Filter, faDirectory, Searcher ) = 0 then
begin
repeat
Data.Source := Source + Searcher.Name;
Data.Destiny := Destiny + Searcher.Name;
Callback( Self, Data )
until FindNext( Searcher ) <> 0;
FindClose( Searcher );
end;

if Data.Recurse and ( FindFirst( Source + '*', faArchive, Searcher ) = 0 ) then
begin
repeat
if Searcher.Name[1] <> '.' then
begin
New( X );
X^.Source := CopyString( AddSlash( Source + Searcher.Name ) );
X^.Destiny := CopyString( AddSlash( Destiny + Searcher.Name ) );
Stack.Push( X );
end;
un

C convert buffer to binary string

// Sometimes one wants to see data in binary
// This method converts an arbitrary buffer to 1's and 0's

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>

char *getBufferAsBinaryString(void *in)
{
	int pos=0;
	char result;
	char bitstring[256];
	memset(bitstring, 0, 256);
	unsigned int *input= (unsigned int *)in;
	for(int i=31;i>=0;i--)
	{
		if (((*input >> i) & 1)) result = '1';
		else result = '0';
		bitstring[pos] = result;
		if ((i>0) && ((i)%4)==0)
		{
			pos++;
			bitstring[pos] = ' ';
		}
		pos++;
	}
	return bitstring;
}
int main(int argc, char* argv[])
{
	int i=53003;
	char buffer[1024];
	char *s=getBufferAsBinaryString(&i);
	strcpy(buffer, s);
	printf("%s\n", buffer);
}


produces this output:
0000 0000 0000 0000 1100 1111 0000 1011

Csharp formatting an integer as a binary string representation

// description of your code here

using System;

namespace testApp
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Class1 t = new Class1();
			long i = 12; // 
			Console.WriteLine(t.ConvertByteToBinaryString(i));
		}
		/// <summary>
		/// Format integer as a binary string with spaces between every 4 bits
		/// </summary>
		/// <param name="input">integer to format</param>
		/// <returns>string of the form "0000 0000 0000 0000 0000 0110 0001 1000"</returns>
		private string ConvertByteToBinaryString(long input)
		{
			string result = null;
			string bitstring = null;
			for(int i=31;i>=0;i--)
			{
				if (((input >> i) & 1) == 1) result = "1";
				else result = "0";
				bitstring += result;
				if ((i>0) && ((i)%4)==0)
				{
					bitstring += " ";
				}
			}
			return bitstring;
		}
	}
}

produces this output:
0000 0000 0000 0000 0000 0000 0000 1100

Using base64 to encode/decode data

If you have binary data, you can encode it with
ascii character to store it more safely.
base64 module is an efficient choice to do so.
It uses characters from this set
('=' is used for padding at the end.)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
0123456789+/

Here's how to use it.
>>> import base64
>>> base64.encodestring('hello world')
'aGVsbG8gd29ybGQ=\n'
>>> base64.decodestring(_)
'hello world'
>>>

If the text is long, the base64 module will split
the encoded data into multiple lines.
If you don't wan't it to be split. You can use
binascii.b2a_base64 instead of base64.encodestring and
binascii.a2b_base64 instead of base64.decodestring

Binary Data Parser //Javascript Class



This is a prototyped class written to serialize and unserialize binary data, so you can read and write binary data files to exchange with programs written in languages like C and Pascal.

Currently the class is able to handle just the following types: signed integers (small 8 bits, short 16 bits, int 32 bits), unsigned integers (byte 8 bits, word 16 bits, dword 32 bits) and floating point (IEEE754 float 32 bits and double 64 bits).

The endianess of the binary values representation can also be configured with the class.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


There's a php version right here.

Code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/binary-parser [v1.0]

BinaryParser = function( bigEndian, allowExceptions ){
	this.bigEndian = bigEndian;
	this.allowExceptions = allowExceptions;
};
with( { p: BinaryParser.prototype } ){
	with( {p: ( p.Buffer = function( bigEndian, buffer ){ this.bigEndian = bigEndian || 0; this.buffer = []; this.setBuffer( buffer ); } ).prototype } ){
		p.setBuffer = function( data ){
			if( data ){
				for( var l, i = l = data.length, b = this.buffer = new Array( l ); i; b[l - i] = data.charCodeAt( --i ) );
				this.bigEndian && b.reverse();
			}
		};
		p.hasNeededBits = function( neededBits ){
			return this.buffer.length >= -( -neededBits >> 3 );
		};
		p.checkBuffer = function( neededBits ){
			if( !this.hasNeededBits( neededBits ) )
				throw new Error( "checkBuffer::missing bytes" );
		};
		p.readBits = function( start, length ){
			//shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
			function shl( a, b ){
				for( ; b--; a = ( ( a %= 0x7fffffff + 1 ) & 0x40000000 ) == 0x40000000 ? a * 2 : ( a - 0x40000000 ) * 2 + 0x7fffffff + 1 );
				return a;
			}
			if( start < 0 || length <= 0 )
				return 0;
			this.checkBuffer( start + length );
			for( var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - ( start >> 3 ) - 1, lastByte = this.buffer.length + ( -( start + length ) >> 3 ), diff = curByte - lastByte, sum = ( ( this.buffer[ curByte ] >> offsetRight ) & ( ( 1 << ( diff ? 8 - offsetRight : length ) ) - 1 ) ) + ( diff && ( offsetLeft = ( start + length ) % 8 ) ? ( this.buffer[ lastByte++ ] & ( ( 1 << offsetLeft ) - 1 ) ) << ( diff-- << 3 ) - offsetRight : 0 ); diff; sum += shl( this.buffer[ lastByte++ ], ( diff-- << 3 ) - offsetRight ) );
			return sum;
		};
	}
	p.warn = function( msg ){
		if( this.allowExceptions )
			throw new Error( msg );
		return 1;
	};
	p.decodeFloat = function( data, precisionBits, exponentBits ){
		var b = new this.Buffer( this.bigEndian, data );
		b.checkBuffer( precisionBits + exponentBits + 1 );
		var bias = Math.pow( 2, exponentBits - 1 ) - 1, signal = b.readBits( precisionBits + exponentBits, 1 ), exponent = b.readBits( precisionBits, exponentBits ), significand = 0,
		divisor = 2, curByte = b.buffer.length + ( -precisionBits >> 3 ) - 1;
		do
			for( var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
		while( precisionBits -= startBit );
		return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
	};
	p.decodeInt = function( data, bits, signed ){
		var b = new this.Buffer( this.bigEndian, data ), x = b.readBits( 0, bits ), max = Math.pow( 2, bits );
		return signed && x >= max / 2 ? x - max : x;
	};
	p.encodeFloat = function( data, precisionBits, exponentBits ){
		var bias = Math.pow( 2, exponentBits - 1 ) - 1, minExp = -bias + 1, maxExp = bias, minUnnormExp = minExp - precisionBits,
		status = isNaN( n = parseFloat( data ) ) || n == -Infinity || n == +Infinity ? n : 0,
		exp = 0, len = 2 * bias + 1 + precisionBits + 3, bin = new Array( len ),
		signal = ( n = status !== 0 ? 0 : n ) < 0, n = Math.abs( n ), intPart = Math.floor( n ), floatPart = n - intPart,
		i, lastBit, rounded, j, result;
		for( i = len; i; bin[--i] = 0 );
		for( i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor( intPart / 2 ) );
		for( i = bias + 1; floatPart > 0 && i; ( bin[++i] = ( ( floatPart *= 2 ) >= 1 ) - 0 ) && --floatPart );
		for( i = -1; ++i < len && !bin[i]; );
		if( bin[( lastBit = precisionBits - 1 + ( i = ( exp = bias + 1 - i ) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - ( exp = minExp - 1 ) ) ) + 1] ){
			if( !( rounded = bin[lastBit] ) )
				for( j = lastBit + 2; !rounded && j < len; rounded = bin[j++] );
			for( j = lastBit + 1; rounded && --j >= 0; ( bin[j] = !bin[j] - 0 ) && ( rounded = 0 ) );
		}
		for( i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i]; );
		if( ( exp = bias + 1 - i ) >= minExp && exp <= maxExp )
			++i;
		else if( exp < minExp ){
			exp != bias + 1 - len && exp < minUnnormExp && this.warn( "encodeFloat::float underflow" );
			i = bias + 1 - ( exp = minExp - 1 );
		}
		if( intPart || status !== 0 ){
			this.warn( intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status );
			exp = maxExp + 1;
			i = bias + 2;
			if( status == -Infinity )
				signal = 1;
			else if( isNaN( status ) )
				bin[i] = 1;
		}
		for( n = Math.abs( exp + bias ), j = exponentBits + 1, result = ""; --j; result = ( n % 2 ) + result, n = n >>= 1 );
		for( n = 0, j = 0, i = ( result = ( signal ? "1" : "0" ) + result + bin.slice( i, i + precisionBits ).join( "" ) ).length, r = []; i; j = ( j + 1 ) % 8 ){
			n += ( 1 << j ) * result.charAt( --i );
			if( j == 7 ){
				r[r.length] = String.fromCharCode( n );
				n = 0;
			}
		}
		r[r.length] = n ? String.fromCharCode( n ) : "";
		return ( this.bigEndian ? r.reverse() : r ).join( "" );
	};
	p.encodeInt = function( data, bits, signed ){
		var max = Math.pow( 2, bits );
		( data >= max || data < -( max >> 1 ) ) && this.warn( "encodeInt::overflow" ) && ( data = 0 );
		data < 0 && ( data += max );
		for( var r = []; data; r[r.length] = String.fromCharCode( data % 256 ), data = Math.floor( data / 256 ) );
		for( bits = -( -bits >> 3 ) - r.length; bits--; r[r.length] = "\0" );
		return ( this.bigEndian ? r.reverse() : r ).join( "" );
	};
	p.toSmall    = function( data ){ return this.decodeInt( data,  8, true  ); };
	p.fromSmall  = function( data ){ return this.encodeInt( data,  8, true  ); };
	p.toByte     = function( data ){ return this.decodeInt( data,  8, false ); };
	p.fromByte   = function( data ){ return this.encodeInt( data,  8, false ); };
	p.toShort    = function( data ){ return this.decodeInt( data, 16, true  ); };
	p.fromShort  = function( data ){ return this.encodeInt( data, 16, true  ); };
	p.toWord     = function( data ){ return this.decodeInt( data, 16, false ); };
	p.fromWord   = function( data ){ return this.encodeInt( data, 16, false ); };
	p.toInt      = function( data ){ return this.decodeInt( data, 32, true  ); };
	p.fromInt    = function( data ){ return this.encodeInt( data, 32, true  ); };
	p.toDWord    = function( data ){ return this.decodeInt( data, 32, false ); };
	p.fromDWord  = function( data ){ return this.encodeInt( data, 32, false ); };
	p.toFloat    = function( data ){ return this.decodeFloat( data, 23, 8   ); };
	p.fromFloat  = function( data ){ return this.encodeFloat( data, 23, 8   ); };
	p.toDouble   = function( data ){ return this.decodeFloat( data, 52, 11  ); };
	p.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11  ); };
}

Generic base conversor //Javascript Object


Minimum Common Multiple

[UPDATED CODE AND HELP CAN BE FOUND HERE]


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/base-conversor [v1.0]

Conversor = {
	h: '0123456789abcdefghijklmnopqrstuvwxyz',

	int2base: function( n, base ){
		if( base < 2 || base > this.h.length )
			throw new Error( "base inválida" );
		for( var n = parseInt( n ) || 0, result = ""; n; result = this.h.charAt( n % base ) + result, n = Math.floor( n / base ) );
		return result;
	},
	base2int: function( s, base ){
		for( var i = -1, l = s.length, result = 0; ++i < l; result = result * base + this.h.indexOf( s.charAt( i ) ) );
		return result;
	}
}

C memory manager "MemoryBlock "

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

#ifndef __MEMORYBLOCK__
#define __MEMORYBLOCK__


//-- includes -----------------------------------------------
#include <stdio.h>
#include <stdlib.h>



//-- data types ---------------------------------------------
typedef struct _MemoryBlock {
	void *data;
	size_t capacity, used, dataSize;
}* MemoryBlock;



//-- functions ----------------------------------------------
MemoryBlock getMemoryBlock( register const size_t dataSize, register const size_t initialSize ){

	MemoryBlock mb = (MemoryBlock)malloc( sizeof( struct _MemoryBlock ) );
	
	if( mb ) {
		mb->used = 0;
		mb->data = NULL;
		mb->dataSize = dataSize;
		mb->capacity = initialSize && ( mb->data = (void *)malloc( initialSize * dataSize ) ) ? initialSize : 0;
	}
	return mb;
}

void freeMemoryBlock( register const MemoryBlock mb ){
	free( mb->data );
	free( mb );
}

int resizeMemoryBlock( register const size_t newSize, register const MemoryBlock mb ){

	void *newData = (void *)realloc( mb->data, newSize * mb->dataSize );

	if( newData ){
		mb->data = newData;
		return mb->capacity = newSize;
	}
	return 0;
}

int growMemoryBlock( register const MemoryBlock mb ){

	size_t delta = mb->capacity > 64 ? mb->capacity / 4 : mb->capacity > 8 ? 16 : 4;
	void *newData = (void *)realloc( mb->data, ( mb->capacity + delta ) * mb->dataSize );

	if( newData ){
		mb->data = newData;
		return mb->capacity += delta;
	}
	return 0;
}

int growExMemoryBlock( register const size_t neededBlocks, register const MemoryBlock mb ){
	while( mb->used+neededBlocks > mb->capacity )
		if( !growMemoryBlock( mb ) )
			return 0;
	return 1;
}

int incMemoryBlock( register const MemoryBlock mb ){
	return  mb->used+1 <= mb->capacity || growMemoryBlock( mb );
}

#endif

a binary tree structure "PersistentTree"

unit StreamAdapter.pas

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

unit StreamAdapter;

interface

uses
  Classes;

type
  IStream = interface( IInterface )
    ['{FBEF199A-09BC-4B61-89EA-1EF8B22C93A5}']
    function Read(var Buffer; const Count: Longint): Longint;
    function Write(const Buffer; const Count: Longint): Longint;
    function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
    procedure ReadBuffer(var Buffer; const Count: Longint);
    procedure WriteBuffer(const Buffer; const Count: Longint);
    function CopyFrom(Source: TStream; const Count: Int64): Int64;
    function WriteTo(Dest: TStream; const Count: Int64): Int64;

    procedure SetPosition( const Value: Int64 );
    procedure SetSize( const Value: Int64 );
    function GetPosition: Int64;
    function GetSize: Int64;

    property Position: Int64 read GetPosition write SetPosition;
    property Size: Int64 read GetSize write SetSize;
  end;

  TStreamAdapter = class( TInterfacedObject, IStream )
  private
    FStream: TStream;
    procedure SetPosition( const Value: Int64 );
    procedure SetSize( const Value: Int64 );
    function GetPosition: Int64;
    function GetSize: Int64;

  public
    constructor Create( Stream: TStream );
    destructor Destroy; override;

    function Read(var Buffer; const Count: Longint): Longint;
    function Write(const Buffer; const Count: Longint): Longint;

    procedure ReadBuffer(var Buffer; const Count: Longint);
    procedure WriteBuffer(const Buffer; const Count: Longint);

    function CopyFrom(Source: TStream; const Count: Int64): Int64;
    function WriteTo(Dest: TStream; const Count: Int64): Int64;

    function Seek(const Offset