0

I have a whole bunch of hex strings (56 bits or 112 bits), which I need to extract different parts from, after converting to a binary string.

How I would normally do it is either substring the parts, or try my luck with bit shifting, but instead of having ~20 lines of Integer.parseInt(binary.substring(...)), I would like to apply some kind of pattern to it.

Any ideas, other than mine below, which is kind of stupid and slow; how to extract a-b, c-d, x-y parts of a binary string? I guess one would need to apply bit shifting, but that would also take multiple lines. I'm fine with a couple of lines, but I really dislike the ~20 substring calls.

Here's my attempt at something like this.

    String p = "(?<df>\\d{5})(?<ca>\\d{3})(?<aa>\\d{24})(?<pl>\\d{0,56})(?<pi>(\\d{24}))";
    String packet = "1000110101010000001011001010010110011001000100010110111100100000010010000000010010001000001010111001101101101010";
    Pattern pattern = Pattern.compile(p);
    Matcher matcher = pattern.matcher(packet);

    while (matcher.find())
        System.out.printf("df=%s, ca=%s, aa=%s, pl=%s, pi=%s\n", matcher.group("df"),
                matcher.group("ca"), matcher.group("aa"), matcher.group("pl"), matcher.group("pi"));

Output:

df=10001, ca=101, aa=010100000010110010100101, pl=10011001000100010110111100100000010010000000010010001000, pi=001010111001101101101010
df=10001, ca=101, aa=010100000010110010100101, pl=10011001000100010110111100100000010010000000010010001000, pi=001010111001101101101010
df=10001, ca=101, aa=010100000010110010100101, pl=10011001000100010110111100100000010010000000010010001000, pi=001010111001101101101010

Any ideas are greatly appreciated

Benny Mose
  • 694
  • 1
  • 8
  • 15
  • If you really have a variable-length field (`pl` in your example code), the regex is probably the best way to do it. – VGR Jan 08 '15 at 01:03
  • 2
    You might want to post this on Code Review (if your code is already working, but you want to improve it). It gets more view than here. – nhahtdh Jan 08 '15 at 03:48
  • @VRG: it's variable length in the sense that, when bit length of the hex string is 56, it's not there, but it is when bit length is 112 :). Thanks for reading – Benny Mose Jan 08 '15 at 06:15
  • @nhahtdh: Oh, I wasn't aware of such a site - that makes sense. I'll leave this open for a bit, and ifs calm, post it on code review. Thanks! – Benny Mose Jan 08 '15 at 06:17

0 Answers0