2014-07-06 4 views
-6

문자열의 처음 2 바이트를 가져 오려고합니다. 예를 들어 "안녕하세요"진에 있습니다 자바에서 문자열의 처음 두 바이트를 가져 오는 방법은 무엇입니까?

01101000 01101001 00100000 01110100 01101000 01100101 01110010 01100101 

내가이 사건 01101000 01101001입니다에있는 바이너리의 처음 두 바이트를 원한다.

+0

문자열을 바이트로 변환하는 코드가 있습니까? 그렇다면 게시하십시오. – Talha

+0

문자열을 이진수로 변환 했으니 까. – TheGathron

+0

당신은'myString [0]'과'myString [1]'을 할 것입니다. 문자열의 데이터는 이미 * 바이너리입니다. 이제 이들 바이트를 "문자 바이너리"로 표시하려면 데이터를 변환해야합니다. 각 바이트를 8 바이트의 문자 데이터로 변환하십시오. 이것은 좋은 초보자의 운동이 될 것입니다. –

답변

-1

이 함수는 입력 문자열과 비트로 변환 할 바이트 수를 사용합니다. 다음과 같이 호출 : getBits를 ("안녕하세요", 2)

public String getBits(String str, int count) { 
    String out = ""; //output string 
    byte[] content = str.getBytes(); //get the bytes from the input string to convert each byte to bits later 
    for(int k=0;k!=count;k++) { //go through the bytes 
     String binary = Integer.toBinaryString(content[k]); //convert byte to a bit string 
     if(binary.length()<8) { //toBinaryString just outputs necessary bits so we have to add some 
      for(int i=0;i<=(8-binary.length());i++) { 
       binary = "0"+binary; //add 0 at front 
      } 
     } 
     out = out + binary; //add it to the output string 
    } 
    return out; 
} 
+0

이 줄에 오류가 나타납니다. \t \t 문자열 getBits (String str, int count) {토큰에 구문 오류가 있습니다. "(", "expected"토큰에 구문 오류 ","예상 " \t" 예상 \t out은 변수 – TheGathron

+0

으로 해결할 수 없습니다. 여기에서 잘 작동합니다. – ByteBit

+0

this get String getBits (String str, int count) {오류가 발생했습니다. – TheGathron

0

기본 접근 방식. 바이트 배열로 변환 한 다음 필요에 따라 형식을 지정합니다.

public class Main { 
    public static void main(String[] args) {   
     StringBuilder result = getBinary("hi there", 2);   
     System.out.println(result.toString());  
     } 

    public static StringBuilder getBinary(String str, int numberOfCharactersWanted) { 
     StringBuilder result = new StringBuilder(); 
     byte[] byt = str.getBytes();  
     for (int i = 0; i < numberOfCharactersWanted; i++) {   
      result.append(String.format("%8s", Integer.toBinaryString(byt[i])).replace(' ', '0')).append(' '); 
     } 
     return result; 
    } 
} 
관련 문제