简体   繁体   中英

Convert each character of a string in bits

 String message= "10";
        byte[] bytes = message.getBytes();

        for (int n = 0; n < bytes.length; n++) {
            byte b = bytes[n];

            for (int i = 0; i < 8; i++) {//do something for each bit in my byte
            boolean bit = ((b >> (7 - i) & 1) == 1);
            }
        }

My problem here is that it takes 1 and 0 as their ASCII values, 49 and 48 , instead of 1 and 0 as binary( 00000001 and 00000000 ). How can I make my program treat each character from my string as a binary sequence of 8 bits?

Basicly, I want to treat each bit of my number as a byte. I do that like this byte b = bytes[n]; but the program treats it as the ASCII value.

I could assign the number to an int, but then, I can't assign the bits to a byte.

It's a bit messy, but the first thing that comes to mind is to first, split your message up into char values, using the toCharArray() method. Next, use the Character.getNumericValue() method to return the int , and finally Integer.toBinaryString .

String message = "123456";

for(char c : message.toCharArray())
{
    int numVal = Character.getNumericValue(c);
    String binaryString = Integer.toBinaryString(numVal);

    for(char bit : binaryString)
    {
         // Do something with your bits.
    }
}
String msg = "1234";

for(int i=0 ; i<msg.length() ; i++ ){
    String bits = Integer.toBinaryString(Integer.parseInt(msg.substring(i, i+1)));
   for(int j=0;j<8-bits.length();j++)
      bits = "0"+bits;
}

Now bits is a string of length 8.

1 00000001 10 00000010 11 00000011 100 00000100

You can use getBytes() on the String

Use Java 's parseInt(String s, int radix) :

String message= "10";
int myInt = Integer.parseInt(message, 2); //because we are parsing it as base 2

At that point you have the correct sequence of bits, and you can do your bit-shifting.

boolean[] bits = new boolean[message.length()];
System.out.println("Parsed bits: ");
for (int i = message.length()-1; i >=0  ; i--) {
    bits[i] = (myInt & (1 << i)) != 0;
    System.out.print(bits[i] ? "1":"0");
}

System.out.println();

You could make it byte s if you really want to, but booleans are a better representation of bits...

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