简体   繁体   中英

String to binary?

I have a very odd situation,

I'm writing a filter engine for another program, and that program has what are called "save areas". Each of those save areas is numbered 0 through 32 (why there are 33 of them, I don't know). They are turned on or off via a binary string,

1 = save area 0 on
10 = save area 1 on, save area 0 off
100 = save area 2 on, save areas 1 and 0 off.

and so on.

I have another program passing in what save areas it needs, but it does so with decimal representations and underscores - 1_2_3 for save areas 1, 2, and 3 for instance.

I would need to convert that example to 1110.

What I came up with is that I can build a string as follows: I break it up (using split) into savePart[i]. I then iterate through savePart[i] and build strings:

String saveString = padRight("0b1",Integer.parseInt(savePart[i]));

That'll give me a string that reads "0b1000000" in the case of save area 6, for instance.

Is there a way to read that string as if it was a binary number instead. Because if I were to say:

long saveBinary = 0b1000000L

that would totally work.

or, is there a smarter way to be doing this?

long saveBinary = Long.parseLong(saveString, 2);

请注意,您必须保留0b前缀。

This will do it:

String input = "1_2_3";
long areaBits = 0;
for (String numTxt : input.split("_")) {
    areaBits |= 1L << Integer.parseInt(numTxt);
}
System.out.printf("\"%s\"  ->  %d (decimal)  =  %<x (hex)  =  %s (binary)%n",
                  input, areaBits, Long.toBinaryString(areaBits));

Output:

"1_2_3"  ->  14 (decimal)  =  e (hex)  =  1110 (binary)

Just take each number in the string and treat it as an exponent. Accumulate the total for each exponent found and you will get your answer w/o the need to remove prefixes or suffixes.

    // will contain our answer
    long answer = 0;

    String[] buckets = givenData.split("_"); // array of each bucket wanted, exponents
    for (int x = 0; x < buckets.length; x++){ // iterate through all exponents found
        long tmpLong = Long.parseLong(buckets[x]); // get the exponent
        answer = (10^tmpLong) + answer; // add 10^exponent to our running total
    }

answer will now contain our answer in the format 1011010101 (what have you).

In your example, the given data was 1_2_3. The array will contain {"1", "2", "3"}

We iterate through that array...

10^1 + 10^2 + 10^3 = 10 + 100 + 1000 = 1110

I believe this is also why your numbers are 0 - 32. x^0 = 1, so you can dump into the 0 bucket when 0 is in the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM