Over a million developers have joined DZone.

To Pack 8bit To 7bit Hex

·
// description of your code here


public static byte[] getSeptets(byte[] octetBytes, boolean hasUDH) throws IOException {
	byte[] compressedData = null;
	try {
		ByteArrayOutputStream bas = new ByteArrayOutputStream();
		int userDataHeaderLen = 0;
		int padBits = 0;
		int userDataLen = octetBytes.length;

		if (hasUDH) {
			userDataHeaderLen = (octetBytes[0] & 0xFF) + 1; // plus 1 za
			// prvi byte
			// duzine
			bas.write(octetBytes, 0, userDataHeaderLen);

			userDataLen = octetBytes.length - userDataHeaderLen;
			padBits = (userDataHeaderLen * 8) % 7;
			if (padBits != 0)
				padBits = 7 - padBits;
		}

		byte pack[] = pack(octetBytes, userDataHeaderLen, userDataLen, padBits);
		bas.write(pack, 0, pack.length);

		compressedData = bas.toByteArray();

	} catch (Throwable e) {
		throw new IOException("Exception in (8bit to 7bit Hex conversion)", e);
	}

	return compressedData;
}

public static byte[] pack(byte[] ba) {
	return pack(ba, 0, ba.length, 0);
}

public static byte[] pack(byte[] ba, int off, int len, int pad) {
	String m1 = "", m2 = "";

	for (int i = 0; i < pad; i++)
		m1 += "0";
	for (int i = off; i < off + len; i++)
		m1 = zeroPad(Integer.toBinaryString(ba[i] & 0x7F), 7) + m1;
	if (m1.length() % 8 != 0)
		m1 = zeroPad(m1, m1.length() + (8 - m1.length() % 8));
	for (int i = 0; i < m1.length(); i += 8) {
		int b = Integer.parseInt(m1.substring(i, i + 8), 2);
		m2 = zeroPad(Integer.toHexString(b).toUpperCase(), 2) + m2;
	}
	return fromHexString(m2);
}

public static byte[] unpack(byte[] ba, int unpack_len) {
	return unpack(ba, 0, ba.length, 0, unpack_len);
}

public static byte[] unpack(byte[] ba, int off, int len, int pad, int unpack_len) {
	String m1 = "", m2 = "";
	for (int i = off; i < off + len; i++) {
		m1 = zeroPad(Integer.toBinaryString(ba[i] & 0xFF), 8) + m1;
	}
	m1 = m1.substring(0, m1.length() - pad);
	m1 = m1.substring(m1.length() % 7);
	for (int i = 0; i < m1.length(); i += 7) {
		int b = Integer.parseInt(m1.substring(i, i + 7), 2);
		m2 = zeroPad(Integer.toHexString(b).toUpperCase(), 2) + m2;
	}
	m2 = m2.substring(0, unpack_len * 2);
	return fromHexString(m2);
}

private static String zeroPad(String s, int p) {
	while (s.length() < p)
		s = "0" + s;
	return s;
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}