Java - Text2Hex - First Draft |
||
![]() Cpt SAJChurchey The Hex conversions are pretty much the same as the binary conversions. All I had to do was change a few things here in there for the Hex case: public static String text2Hex(String str){
if(str == null || str.trim().length() == 0)
//Matches NULL and whitespace case
return "";
str = str.trim(); //Gets rid of leading/trailing whitespace
int strlen = str.length();
StringBuffer hexString = new StringBuffer((strlen * 3));
/*
Assuming all UTF-8 input. The capacity of the buffer
needs to be strlen * 3. This cuts down on what can
be a time consuming dynamic resizing on large input
sets. Should only resize once at most, and only if
the input contains a UTF-16 character.
*/
for(int i=0;i < strlen;++i){ //Iterates through string
int decimal = str.charAt(i); //Gets "ASCII value"
String hex = Integer.toHexString(decimal);
if(decimal <= 255){
/*
This case tests for ASCII, Extended ASCII and UTF-8
integer values. It completes the octet for these
8-bit encodings by padding with leading zeros.
*/
int trailingZeros = 2 - hex.length();
for(int j = 0; j < trailingZeros;++j)
hexString.append("0");
}//end if
else{ //UTF-16
/*
This case completes the 16-bit encoding of UTF-16
characters by padding with leading zeros
*/
int trailingZeros = 4 - hex.length();
for(int k = 0;k < trailingZeros;++k)
hexString.append("0");
}//end else
hexString.append(hex);
//Adds hexadecimal representation to generated leading zeros.
hexString.append(" ");
}//end for
return hexString.toString();
}//end text2Hex()
Cpt SAJChurchey
C/O of Editorial OSI Staff edit0r OSI Feedback Representative Replies:
|
||
| CyberArmy::Forum v0.6 Generated In 0.02396 seconds |