Pergunta

String seq= "101010101";
byte[] bytes = seq.getBytes();

for (int i = 0; i < bytes.length; i++) {
    byte b=bytes[i]; 
    System.out.println(b);
}

It will print ASCII codes for 1 and 0, which are 48 and 49. I want to print 1 and 0. How can I do that?

Foi útil?

Solução

String seq= "101010101";
 char[] bits = seq.toCharArray();

   for (int i = 0; i < bits.length; i++) {
                char b=bits[i]; 
                System.out.println(b);
  }

Outras dicas

String seq= "101010101";
char[] charArray = seq.toCharArray();

for (int i = 0; i < charArray.length; i++) {
            char b=charArray[i]; 
            System.out.println(b);
}

You can just do b - 48 to print 1 or 0.

System.out.println(b - 48);

Your sequence is a String containing the characters 0 and 1. It is not a sequence of binary numbers. getBytes() give you the bytes of each of the characters in your String. What you want is to just iterate over the characters in your String.

for (char c : seq.toCharArray()) {
  System.out.println(c);
}

Sounds like you really want to use the following loop:

String seq = "101010101";
for (int=0; i < seq.length; i++) {
   String s = seq.substring(i,i+1);
   ... or char c = seg.charAt(i);
   System.out.println(s) .. (or c)
}

Why are you trying to use bytes?

Use the following code:

final int ASCII_0 = 48;
String seq= "101010101";
byte[] bytes = seq.getBytes();

for (int i = 0; i < bytes.length; i++) {
    byte b=bytes[i]; 
    System.out.println(b - ASCII_0);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top