tweetcast/client/lib/websocket-js/flash-src/third-party/com/hurlant/util/Hex.as
changeset 311 13702105c5ee
parent 310 526d3e411736
child 312 f8336354d107
child 314 0f1e6ce19b6d
equal deleted inserted replaced
310:526d3e411736 311:13702105c5ee
     1 /**
       
     2  * Hex
       
     3  * 
       
     4  * Utility class to convert Hex strings to ByteArray or String types.
       
     5  * Copyright (c) 2007 Henri Torgemane
       
     6  * 
       
     7  * See LICENSE.txt for full license information.
       
     8  */
       
     9 package com.hurlant.util
       
    10 {
       
    11 	import flash.utils.ByteArray;
       
    12 	
       
    13 	public class Hex
       
    14 	{
       
    15 		/**
       
    16 		 * Support straight hex, or colon-laced hex.
       
    17 		 * (that means 23:03:0e:f0, but *NOT* 23:3:e:f0)
       
    18 		 * Whitespace characters are ignored.
       
    19 		 */
       
    20 		public static function toArray(hex:String):ByteArray {
       
    21 			hex = hex.replace(/\s|:/gm,'');
       
    22 			var a:ByteArray = new ByteArray;
       
    23 			if (hex.length&1==1) hex="0"+hex;
       
    24 			for (var i:uint=0;i<hex.length;i+=2) {
       
    25 				a[i/2] = parseInt(hex.substr(i,2),16);
       
    26 			}
       
    27 			return a;
       
    28 		}
       
    29 		
       
    30 		public static function fromArray(array:ByteArray, colons:Boolean=false):String {
       
    31 			var s:String = "";
       
    32 			for (var i:uint=0;i<array.length;i++) {
       
    33 				s+=("0"+array[i].toString(16)).substr(-2,2);
       
    34 				if (colons) {
       
    35 					if (i<array.length-1) s+=":";
       
    36 				}
       
    37 			}
       
    38 			return s;
       
    39 		}
       
    40 		
       
    41 		/**
       
    42 		 * 
       
    43 		 * @param hex
       
    44 		 * @return a UTF-8 string decoded from hex
       
    45 		 * 
       
    46 		 */
       
    47 		public static function toString(hex:String):String {
       
    48 			var a:ByteArray = toArray(hex);
       
    49 			return a.readUTFBytes(a.length);
       
    50 		}
       
    51 		
       
    52 		
       
    53 		/**
       
    54 		 * 
       
    55 		 * @param str
       
    56 		 * @return a hex string encoded from the UTF-8 string str
       
    57 		 * 
       
    58 		 */
       
    59 		public static function fromString(str:String, colons:Boolean=false):String {
       
    60 			var a:ByteArray = new ByteArray;
       
    61 			a.writeUTFBytes(str);
       
    62 			return fromArray(a, colons);
       
    63 		}
       
    64 		
       
    65 	}
       
    66 }