/*
 * Hex_Convert.bsh - a BeanShell macro script for the
 * jEdit text editor - Converts byte characters to their
 * hex equivalent, and vice versa.
 * Copyright (C) 2001 Will Sargent
 * will_sargent@yahoo.dom
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the jEdit program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: Hex_Convert.bsh 5224 2005-06-08 22:33:27Z orutherfurd $
 */

import java.io.*;
import java.util.*;

char[] hexDigit = new char[]
{
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};

String byteToHex(byte b)
{
    char[] chars = new char[]
    {
        hexDigit[(b >> 4) & 0x0f],
        hexDigit[b & 0x0f]
    };
    return new String(chars);
}

void print(String line)
{
    Macros.message(view, line);
}

void stringToByte(String target)
{
    byte[] string = target.getBytes();

    StringBuffer foo = new StringBuffer();
    foo.append("before = " + target);
    foo.append("\nafter = ");

    int length = string.length;
	for (int i = 0; i < length; i++)
    {
		foo.append("0x" + byteToHex(string[i]));
        if (i < length - 1) foo.append(" ");
    }
    print(foo.toString());
}

void byteToString(String target)
{
	if(target.length() == 0)
		return;

	try
	{
    byte b = Byte.parseByte(target, 16);
    String str = new String(new byte[] { b });

    StringBuffer foo = new StringBuffer();
		foo.append("" + target + " = " + str);

    print(foo.toString());
	}
	catch(NumberFormatException nfe)
	{
		Macros.error(view, "" + target + " is not valid hex string.");
	}
}

String target = Macros.input(view,"Byte to String:");
if(target != null)
	byteToString(target);


/*

Macro index data (in DocBook format)

  <listitem>
    <para><filename>Hex_Convert.bsh</filename></para>
    <abstract><para>
      Converts byte characters to their hex equivalent, and vice versa.
    </para></abstract>
  </listitem>

*/

// end Hex_Convert.bsh

