0

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.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • 2
    @ElliottFrisch - Do you at least understand what exactly OP is asking for? I don't. – PM 77-1 Jan 02 '15 at 03:42
  • 2
    Why 26 bytes? @monsterbasher – Jobs Jan 02 '15 at 03:44
  • 1
    @PM77-1 Like why each `int` should have a different binary width? – Elliott Frisch Jan 02 '15 at 03:44
  • You are being somewhat inconsistent here, regarding the format of the numbers. What if all 4 numbers are 255s? At best, you can write 255 as 11111111, which is 8 binary digits, times 4 is 32. Also, you mention byte array of 26 bytes, which is not consistent with your exammple, because your example has 26 bits – ioreskovic Jan 02 '15 at 03:45
  • 1
    @ElliottFrisch yeah exactly. I'm confused. – Jobs Jan 02 '15 at 03:45
  • Well i'm currently trying to encode a genetic algorithm chromosome and a gene represents each part of the binary string I showed above. And one chromosome represents all those genes combined into a 26 bit string. – monsterbasher Jan 02 '15 at 03:47
  • 1
    But your question asks about `int` (a 4 byte datatype) and `byte` (an 8 bit datatype), nothing in your question gives us any clue as to how or why each field should be at each length. You can always write a function to pad your `String` value with leading zeros. A binary string is **not** a byte array. – Elliott Frisch Jan 02 '15 at 03:50
  • Blah I asked it really weird, I just want to convert an int into a byte array with the leading zeroes added. – monsterbasher Jan 02 '15 at 03:55
  • So just to clarify - you want each byte in your byte array to be either 00000000 or 00000001, right? You're only using one bit from each byte? – Dawood ibn Kareem Jan 02 '15 at 03:58
  • Yeah, I messed up on my part, I'm terribly inexperienced with programming mind you. So I want to convert a int value into it's bit counterpart but have it so there's a set amount of bits. – monsterbasher Jan 02 '15 at 04:08
  • @ElliottFrisch Please use the close reason made for this type of question, i.e. "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers" – Zach Saucier Jan 02 '15 at 04:27
  • Awfully similar to http://stackoverflow.com/q/4421400 – Dawood ibn Kareem Jan 02 '15 at 06:10

2 Answers2

2

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    ... or use the perfectly good `leftPad` method in the Apache commons `StringUtils` class, or something like it. No point in re-inventing wheels. – Dawood ibn Kareem Jan 02 '15 at 05:30
  • @DavidWallace Apache Commons has a lot of high value code in it. But I try to avoid writing answers using third party code unless it has been asked for explicitly in the question. – Elliott Frisch Jan 02 '15 at 05:34
  • It's a shame that you avoid doing that, Elliott, because it means you're missing out on teaching people one of the most valuable lessons of software development - that is, don't repeat someone else's work. – Dawood ibn Kareem Jan 02 '15 at 05:37
  • @DavidWallace Perhaps, but introducing a third-party dependency can cause [issues](http://en.wikipedia.org/wiki/Dependency_hell). Further, [`StringUtils`](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html) is part of [commons-lang](http://commons.apache.org/proper/commons-lang/) and it seems like overkill to add an entire library for one function. – Elliott Frisch Jan 02 '15 at 05:44
  • Couldn't agree less - which means maybe it's time for me to write my own answer! – Dawood ibn Kareem Jan 02 '15 at 06:06
  • @DavidWallace You probably could agree less, I could say something rude, untrue or disparaging about Apache Commons. You can always write your own answer, but don't reinvent the wheel isn't really an answer. :) – Elliott Frisch Jan 02 '15 at 06:20
0

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.

Output

0000001
0001000
1110001
0000100

Code

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();
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132