litesoft
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
package org.litesoft.core.util;
public class Hex
{
private static final String HEX = "0123456789ABCDEF";
public static char toChar( int pZeroTo15 )
{
pZeroTo15 &= 15;
return (pZeroTo15 < 0) || (15 < pZeroTo15) ? '?' : HEX.charAt( pZeroTo15 );
}
/**
* Attempt to interpret (char) pHex as a Hex Character
*
* @return -1 if not a HEX character, otherwise the 0-15
*/
public static int fromChar( char pHex )
{
return HEX.indexOf( Character.toUpperCase( pHex ) );
}
public static int fromCharChecked( char pHex )
throws IllegalArgumentException
{
int rv = fromChar( pHex );
if ( rv == -1 )
{
throw new IllegalArgumentException( "Not a Hex digit '" + pHex + "': " + (int) pHex );
}
return rv;
}
public static char[] to4Chars( char c )
{
char[] rv = new char[4];
int cv = c;
for ( int i = 3; i >= 0; i-- )
{
rv[i] = toChar( cv );
cv /= 16;
}
return rv;
}
public static char from4Chars( char[] pHex )
throws IllegalArgumentException
{
int rv = 0;
for ( char c : pHex )
{
rv = (rv * 16) + fromCharChecked( c );
}
return (char) rv;
}
public static String toHex( byte[] pBytes )
{
if ( pBytes == null )
{
return null;
}
StringBuilder sb = new StringBuilder( pBytes.length + pBytes.length );
for ( byte zByte : pBytes )
{
sb.append( toChar( zByte >>> 4 ) );
sb.append( toChar( zByte ) );
}
return sb.toString();
}
public static byte[] fromHex( String pString )
{
if ( pString == null )
{
return null;
}
if ( (pString.length() & 1) == 1 )
{
throw new IllegalArgumentException( "Can't be HEX as it is 'Odd' Length: '" + pString + "'" );
}
int zCharAt = 0;
byte[] zBytes = new byte[pString.length() / 2];
for ( int i = 0; i < zBytes.length; i++ )
{
int z1st = fromCharChecked( pString.charAt( zCharAt++ ) );
int z2nd = fromCharChecked( pString.charAt( zCharAt++ ) );
zBytes[i] = (byte) ((z1st << 4) + z2nd);
}
return zBytes;
}
}
|
Revision |
Author |
Commited |
Message |
811
|
GeorgeS
|
Sat 18 Aug, 2012 13:45:18 +0000 |
|