简体   繁体   English

将数组字节转换为二进制

[英]Convert array Byte To Binary

please any one can help me to convert the ascciiText to binary such as 49 have binary 00110001 and 48 is 00110010 and so on this is my code 请任何人可以帮助我将ascciiText转换为二进制,例如49具有二进制00110001,而48是00110010,以此类推。

import java.lang.String;
import java.util.Scanner;
import java.lang.*;
import java.io.*;
import java.util.*;

public class encrption {

public static void main(String[] args){

     // INPUT: KeyText   (StrKey).
    // OUTPUT: Ciphertext (ConcatenatedData).
   //String ConcatenatedData; 


    // Read data from user.
    Scanner in = new Scanner(System.in);
    System.out.println("Enter Your PlainText");
    String StrValue = in.nextLine();
    System.out.println("Enter Your KeyText ");
    String StrKey = in.nextLine();

  // Print the Concatenated Data.

 String ConcatenatedData = StrKey.concat(StrValue);
       System.out.println("the Concatenated Data is :"+ConcatenatedData);

  // Convering the Concatenated data to Ascii data.

 try { 
  byte[] asciiText = ConcatenatedData.getBytes("US-ASCII");


    System.out.println(Arrays.toString(asciiText)); 

}

 catch (java.io.UnsupportedEncodingException e)
     { e.printStackTrace(); }

Please any one can help me to convert the series of ascciiText to binary such as 49 have binary 00110001 and 48 is 00110010 and so on 请任何人可以帮助我将ascciiText系列转换为二进制,例如49具有二进制00110001,而48是00110010,依此类推

Configuration: encrption - JDK version 1.8.0_40 配置:加密-JDK版本1.8.0_40

Enter Your PlainText welcome Enter Your KeyText 123 the Concatenated Data is :123welcome [49, 50, 51, 119, 101, 108, 99, 111, 109, 101] 输入您的PlainText欢迎词输入您的KeyText 123级联数据是:123welcome [49、50、51、119、101、108、99、111、109、101]

Process completed. 流程完成。

Since byte doesn't provide any method for this you'll have to use Integer : 由于byte没有为此提供任何方法,因此您必须使用Integer

byte[] b = ...;//you're array
String binStr = "";

for(byte v : b)
    binStr += Integer.toBinaryString(v);

Or you could write your own method. 或者,您可以编写自己的方法。 Wouldn't be too difficult aswell: 也不会太困难:

String toBinary(byte b){
    char[] binArr = new char[8];

    //if a bit is 1, emplace '1' at the respective position in the array, else 0
    for(int i = 0 ; i < 8 ; i++)
        binArr[7 - i] = (b & (1 << i)) == 0 ? '0' : '1';

    return new String(binArr);
}

Simialr on @Paul's solution but written another way. Simialr在@Paul的解决方案上写了另一种方法。

String toBinary(byte b) {
    StringBuilder sb = new StringBuilder(8);

    for(int i = 7 ; i >= 0 ; i--)
        sb.append((char) ('0' + ((b >> i) & 1));

    return sb.toString();
}

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

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