COMP-3 data (or βpacked decimal dataβ) looks like this: 0x12345s, where βsβ is C for positive, D for negative, or F for unsigned. Thus, 0x12345c β β12345β, x012345d β β-12345β and 0x12345f β β12345β.
You have one obvious mistake: you ignore nybble in a byte that contains the nybble character (for example, "5" above) if the character is negative. In addition, you work too much on manipulating nybbles, this is a simple bitwise and / or 4-bit shift to isolate nybble.
Try something like this (untested):
public String unpackData(String packedData, int decimalPointLocation) { String unpackedData = ""; char[] characters = packedData.toCharArray(); final int negativeSign = 13; for (int currentCharIndex = 0; currentCharIndex < characters.length; currentCharIndex++) { byte firstDigit = ((byte) characters[currentCharIndex]) >>> 4); byte secondDigit = ((byte) characters[currentCharIndex]) & 0x0F; unpackedData += String.valueOf(firstDigit); if (currentCharIndex == (characters.length - 1)) { if (secondDigit == negativeSign) { unpackedData = "-" + unpackedData; } } else { unpackedData += String.valueOf(secondDigit); } } if (decimalPointLocation > 0) { unpackedData = unpackedData.substring(0, (decimalPointLocation - 1)) + "." + unpackedData.substring(decimalPointLocation); } return unpackedData; }
source share