Reputation: 65
I'm trying to convert 4 integers from a text file and convert and assign them into a byte array of 26 bytes.
Ex. Text file contains numbers 1
8
113
4
and these four integers are to be placed in this exact sequence consecutively:
001 01000 0001110001 00000100
To further reiterate I want to have 4 bytes set and put an int into, so instead of outputting 2 like this
10
I want it like
0010
Edit: Basically for the example above I just want 4 different byte arrays that have a set length of 3, 5, etc and want to insert an int into each array. Sorry for making it confusing.
Upvotes: 0
Views: 96
Reputation: 48630
Using padding, you can achieve something like the following. String.format("%0{n}d", number)
will not work here since the bitstring is not an integer and you can only prepend/append spaces to a string.
0000001
0001000
1110001
0000100
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
int[] values = { 1, 8, 113, 4 };
int width = -getMaxWidth(values);
for (int value : values) {
System.out.println(prettyPrintBitString(value, width));
}
}
public static String prettyPrintBitString(int value, int padding) {
return pad(Integer.toBinaryString(value), '0', padding);
}
public static int getMaxWidth(int[] values) {
return numberOfBits(Collections.max(toList(values)));
}
public static int numberOfBits(int value) {
return (int) (Math.floor(Math.log(value) / Math.log(2)) + 1);
}
public static List<Integer> toList(int[] values) {
List<Integer> list = new ArrayList<Integer>();
for (int value : values) list.add(value);
return list;
}
public static String pad(String str, char token, int count) {
StringBuilder padded = new StringBuilder(str);
if (count < 0) {
while (padded.length() < -count) padded.insert(0, token);
} else if (count > 0) {
while (padded.length() < count) padded.append(token);
}
return padded.toString();
}
}
Upvotes: 0
Reputation: 201447
If I understand your question, you could start by writing a function to pad a String
with a leading character. Something like
public static String padString(String in, char padChar, int length) {
StringBuilder sb = new StringBuilder(length);
sb.append(in);
for (int i = in.length(); i < length; i++) {
sb.insert(0, padChar);
}
return sb.toString();
}
Then you could call Integer.toBinaryString(int)
and pass the result to padString
like
public static void main(String[] args) {
System.out.println(padString(Integer.toBinaryString(2), '0', 4));
}
Output is (as requested)
0010
Upvotes: 2