简体   繁体   English

以位为单位转换字符串的每个字符

[英]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 ). 我的问题是,它将10作为其ASCII值4948 ,而不是将10作为其二进制值( 0000000100000000 )。 How can I make my program treat each character from my string as a binary sequence of 8 bits? 如何使程序将字符串中的每个字符视为8位二进制序列?

Basicly, I want to treat each bit of my number as a byte. 基本上,我想将数字的每一位都当作一个字节。 I do that like this byte b = bytes[n]; 我这样做就像byte b = bytes[n]; but the program treats it as the ASCII value. 但程序会将其视为ASCII值。

I could assign the number to an int, but then, I can't assign the bits to a byte. 我可以将数字分配给一个int,但是然后,我不能将这些位分配给一个字节。

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. 有点混乱,但是首先想到的是,首先要使用toCharArray()方法将消息拆分为char值。 Next, use the Character.getNumericValue() method to return the int , and finally Integer.toBinaryString . 接下来,使用Character.getNumericValue()方法返回int ,最后返回Integer.toBinaryString

Example

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. 现在,位是一个长度为8的字符串。

1 00000001 10 00000010 11 00000011 100 00000100 1 00000001 10 00000010 11 00000011 100 00000100

You can use getBytes() on the String 您可以在字符串上使用getBytes()

Use Java 's parseInt(String s, int radix) : 使用JavaparseInt(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... 如果确实愿意,可以将其设置为byte ,但是布尔值是位的更好表示...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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