HomeForumSourceResearchGuide
Sign in to contribute to source. how it works
Component data.ByteUtil by barry
expand copy to clipboardexpand
component provides ByteUtil requires io.Output out, data.IntUtil iu, data.StringUtil stringUtil {

	byte[] ByteUtil:reverse(byte bytes[])
		{
		byte reversed[] = new byte[bytes.arrayLength]

		for (int i = 0; i < bytes.arrayLength; i++)
		reversed[i] = bytes[(bytes.arrayLength - 1) - i]

		return reversed
		}

	char[] ByteUtil:toHexString(byte bytes[])
		{
		char hexString[] = ""

		for (int i = 0; i < bytes.arrayLength; i++)
			{
			char upperChar = (bytes[i] & 0xF0) >> 4
			char lowerChar = bytes[i] & 0x0F

			//ascii offsets
			if(upperChar < 10)
			upperChar += 48
			else
			upperChar += 87

			//ascii offsets
			if(lowerChar < 10)
			lowerChar += 48
			else
			lowerChar += 87


			hexString = new char[](hexString,upperChar,lowerChar)
			}

		return hexString
		}

	byte[] ByteUtil:fromHexString(char hexString[])
		{
		byte byteArray[]

		if (hexString.arrayLength % 2 != 0)
			{
			throw new Exception("hex string must be of even length")
			}

		hexString = hexString.lowercase()

		for(int i = 0; i < hexString.arrayLength; i += 2)
			{
			char upperByte = hexString[i]
			char lowerByte = hexString[i+1]

			//ascii offsets
			if(upperByte < 58)
			upperByte -= 48
			else
			upperByte -= 87

			//ascii offsets
			if(lowerByte < 58)
			lowerByte -= 48
			else
			lowerByte -= 87

			byte combined = (upperByte << 4) | lowerByte

			byteArray = new char[](byteArray,combined)
			}

		return byteArray
		}

}
Revision history
To propose a new revision to this entity, use dana source put -uc your/new/version.dn -n data.ByteUtil -m "reason for update" -u yourUsername
Version 3 by barry
Version 2 (this version) by barry
Notes for this version: Adjusts the fromHexString() function to be case-agnostic on its input
Version 1 by barry