01: /*
02: * @(#)hex.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.*;
12: import java.math.*;
13:
14: public class hex extends PnutsFunction {
15: static char[] hex_chars = { '0', '1', '2', '3', '4', '5', '6', '7',
16: '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
17:
18: public hex() {
19: super ("hex");
20: }
21:
22: public boolean defined(int narg) {
23: return (narg == 1);
24: }
25:
26: protected Object exec(Object[] args, Context context) {
27: if (args.length != 1) {
28: undefined(args, context);
29: return null;
30: } else {
31: Object n = args[0];
32: String s;
33: boolean minus;
34: if (n instanceof byte[]) {
35: byte[] b = (byte[]) n;
36: int len = b.length;
37: char[] result = new char[len * 2];
38: for (int i = 0, j = 0; i < len; i++, j += 2) {
39: byte x = b[i];
40: int q = ((x + 256) % 256);
41: result[j] = hex_chars[q >> 4];
42: result[j + 1] = hex_chars[q & 0x0f];
43: }
44: return new String(result);
45: } else if (n instanceof BigInteger) {
46: BigInteger bint = (BigInteger) n;
47: minus = (bint.signum() < 0);
48: s = bint.toString(16);
49: // } else if (n instanceof BigDecimal){
50: // BigDecimal bdec = (BigDecimal)n;
51: // minus = (bdec.signum() < 0);
52: // s = bdec.toBigInteger().toString(16);
53: } else if (n instanceof Long) {
54: long val = ((Long) n).longValue();
55: minus = val < 0;
56: s = Long.toString(val, 16);
57: } else {
58: int val = ((Integer) n).intValue();
59: minus = val < 0;
60: s = Integer.toString(val, 16);
61: }
62: return s;
63: }
64: }
65: }
|