Skip to content

Commit 8d259f3

Browse files
Add functions to format ByteArray as bit string
1 parent 70ce330 commit 8d259f3

File tree

1 file changed

+38
-0
lines changed
  • app/src/main/java/org/vonderheidt/hips/utils

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package org.vonderheidt.hips.utils
2+
3+
/**
4+
* Object (i.e. singleton class) that represents various functions for string formatting.
5+
*/
6+
object Format {
7+
/**
8+
* Function to format a ByteArray as a bit string.
9+
*
10+
* @param byteArray A ByteArray.
11+
* @return The bit string.
12+
*/
13+
fun asBitString(byteArray: ByteArray): String {
14+
val bitString = byteArray.joinToString(separator = "") { byte ->
15+
String.format(format = "%8s", Integer.toBinaryString(byte.toInt() and 0xFF)).replace(oldChar = ' ', newChar = '0')
16+
}
17+
18+
return bitString
19+
}
20+
21+
/**
22+
* Function to reverse formatting of a ByteArray as a bit string (i.e. to reverse `Format.asBitString(ByteArray)`).
23+
*
24+
* @param bitString A bit string.
25+
* @return The ByteArray.
26+
*/
27+
fun asByteArray(bitString: String): ByteArray {
28+
// Don't assert string length to be a multiple of 8, causes error in Huffman encoding with 3 bits/token
29+
val byteArray = ByteArray(size = bitString.length / 8) { index ->
30+
val byteString = bitString.substring(startIndex = index * 8, endIndex = (index + 1) * 8)
31+
val byte = byteString.toInt(radix = 2).toByte()
32+
33+
byte
34+
}
35+
36+
return byteArray
37+
}
38+
}

0 commit comments

Comments
 (0)