大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節點LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 學習攻略 Java學習 Java字符串轉二進制

Java字符串轉二進制

更新時間:2022-12-13 12:05:59 來源:動力節點 瀏覽3003次

1. 字符串轉二進制——Integer.toBinaryString

將字符串轉換為其二進制格式的步驟。

將字符串轉換為char[].

循環char[].

Integer.toBinaryString(aChar)將字符轉換為二進制字符串。

String.format如果需要創建填充。

package com.mkyong.crypto.bytes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StringToBinaryExample1 {
    public static void main(String[] args) {
        String input = "Hello";
        String result = convertStringToBinary(input);
        System.out.println(result);
        // pretty print the binary format
        System.out.println(prettyBinary(result, 8, " "));
    }
    public static String convertStringToBinary(String input) {
        StringBuilder result = new StringBuilder();
        char[] chars = input.toCharArray();
        for (char aChar : chars) {
            result.append(
                    String.format("%8s", Integer.toBinaryString(aChar))   // char -> int, auto-cast
                            .replaceAll(" ", "0")                         // zero pads
            );
        }
        return result.toString();
    }
    public static String prettyBinary(String binary, int blockSize, String separator) {
        List<String> result = new ArrayList<>();
        int index = 0;
        while (index < binary.length()) {
            result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
            index += blockSize;
        }
        return result.stream().collect(Collectors.joining(separator));
    }
}

輸出

0100100001100101011011000110110001101111
01001000 01100101 01101100 01101100 01101111

2. 將字符串轉換為二進制——位掩碼。

(1)此 Java 示例將使用位掩碼技術從 8 位字節生成二進制格式。

package com.mkyong.crypto.bytes;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StringToBinaryExample2 {
    public static void main(String[] args) {
        String input = "a";
        String result = convertByteArraysToBinary(input.getBytes(StandardCharsets.UTF_8));
        System.out.println(prettyBinary(result, 8, " "));
    }
    public static String convertByteArraysToBinary(byte[] input) {
        StringBuilder result = new StringBuilder();
        for (byte b : input) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                result.append((val & 128) == 0 ? 0 : 1);      // 128 = 1000 0000
                val <<= 1;
            }
        }
        return result.toString();
    }
    public static String prettyBinary(String binary, int blockSize, String separator) {
        //... same with 1.1
    }
}

輸出

 01100001

困難的部分是這段代碼。這個想法類似于這個Java – Convert Integer to Binary using bit masking。在Java中,byte一個是8位,int一個是32位,對于整數128二進制是1000 0000.

for (byte b : input) {
    int val = b;                                      // byte -> int
    for (int i = 0; i < 8; i++) {
        result.append((val & 128) == 0 ? 0 : 1);      // 128 = 1000 0000
        val <<= 1;                                    // val = val << 1
    }
}

這&是一個按位與運算符,只有1 & 1,1其他組合都是0。

1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

這val <<= 1實際上是val = val << 1,它是一個位左移運算符,它將位向左移動 1 位。

查看以下草稿:讓我們假設 是val一個int,或者byte代表一個字符a。

00000000 | 00000000 | 00000000 | 01100001   # val  = a in binary
00000000 | 00000000 | 00000000 | 10000000   # 128
&                                           # bitwise AND
00000000 | 00000000 | 00000000 | 00000000   # (val & 128) == 0 ? 0 : 1, result = 0
00000000 | 00000000 | 00000000 | 11000010   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&                                           # bitwise AND
00000000 | 00000000 | 00000000 | 10000000   # (val & 128) == 0 ? 0 : 1, result = 1
00000000 | 00000000 | 00000001 | 10000100   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&
00000000 | 00000000 | 00000000 | 10000000   # result = 1
00000000 | 00000000 | 00000011 | 00001000   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&
00000000 | 00000000 | 00000000 | 00000000   # result = 0
00000000 | 00000000 | 00000110 | 00010000   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&
00000000 | 00000000 | 00000000 | 00000000   # result = 0
00000000 | 00000000 | 00001100 | 00100000   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&
00000000 | 00000000 | 00000000 | 00000000   # result = 0
00000000 | 00000000 | 00011000 | 01000000   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&
00000000 | 00000000 | 00000000 | 00000000   # result = 0
00000000 | 00000000 | 00110000 | 10000000   # val << 1
00000000 | 00000000 | 00000000 | 10000000   # 128
&
00000000 | 00000000 | 00000000 | 10000000   # result = 1
# collect all bits                          # 01100001

對于字符串,a二進制字符串是01100001.

3. 將二進制轉換為字符串。

在Java中,我們可以使用Integer.parseInt(str, 2)將二進制字符串轉換為字符串。

package com.mkyong.crypto.bytes;
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringToBinaryExample3 {
    public static void main(String[] args) {
        String input = "01001000 01100101 01101100 01101100 01101111";
        // Java 8 makes life easier
        String raw = Arrays.stream(input.split(" "))
                .map(binary -> Integer.parseInt(binary, 2))
                .map(Character::toString)
                .collect(Collectors.joining()); // cut the space
        System.out.println(raw);
    }
}

輸出

  Hello

4. 將 Unicode 字符串轉換為二進制。

我們可以使用 Unicode 來表示非英文字符,因為 Java String 支持 Unicode,我們可以使用相同的位掩碼技術將 Unicode 字符串轉換為二進制字符串。

本例將單個漢字你(英文的意思you)轉換為二進制字符串。

package com.mkyong.crypto.bytes;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class UnicodeToBinary1 {
    public static void main(String[] args) {
        byte[] input = "你".getBytes(StandardCharsets.UTF_8);
        System.out.println(input.length);                       // 3, 1 Chinese character = 3 bytes
        String binary = convertByteArraysToBinary(input);
        System.out.println(binary);
        System.out.println(prettyBinary(binary, 8, " "));
    }
    public static String convertByteArraysToBinary(byte[] input) {
        StringBuilder result = new StringBuilder();
        for (byte b : input) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                result.append((val & 128) == 0 ? 0 : 1);      // 128 = 1000 0000
                val <<= 1;
            }
        }
        return result.toString();
    }
    public static String prettyBinary(String binary, int blockSize, String separator) {
        //... same code 1.1
    }
}

輸出

3
111001001011110110100000
11100100 10111101 10100000

不同的 Unicode 需要不同的字節,并不是所有的漢字都需要 3 個字節的存儲,有些可能需要更多或更少的字節。

5. 將二進制轉換為 Unicode 字符串。

閱讀評論以獲得不言自明。

package com.mkyong.crypto.bytes;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class UnicodeToBinary2 {
    public static void main(String[] args) {
        String binary = "111001001011110110100000";     // 你, Chinese character
        String result = binaryUnicodeToString(binary);
        System.out.println(result.trim());
    }
    // <= 32bits = 4 bytes, int needs 4 bytes
    public static String binaryUnicodeToString(String binary) {
        byte[] array = ByteBuffer.allocate(4).putInt(   // 4 bytes byte[]
                Integer.parseInt(binary, 2)
        ).array();
        return new String(array, StandardCharsets.UTF_8);
    }
}

輸出

 

提交申請后,顧問老師會電話與您溝通安排學習

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 亚洲精品在线播放视频 | 中文字幕在线精品视频万部 | 91精品国产免费久久久久久 | 色综合色狠狠天天综合色 | 老司机日日摸夜夜摸精品影院 | 欧美一级日韩在线观看 | 天天天天干 | 午夜在线视频一区二区三区 | 999热精品这里在线观看 | 亚洲伦理| 成人a毛片在线看免费全部播放 | 亚洲视频精品在线 | a毛片基地 | 四虎最新网 | 一级成人a免费视频 | 欧美一级视频 | 亚洲欧美在线精品一区二区 | 日韩va| 亚洲欧洲精品成人久久曰 | 亚洲国产成人久久一区www妖精 | 久久久精品视频在线观看 | 九九热在线免费 | 精品日韩一区二区 | 欧美啊v在线观看 | 亚洲免费视频一区二区三区 | 久久久久久免费精品视频 | 欧美一区二区手机在线观看视频 | 一区二区日韩 | 中文字幕不卡一区2021 | 日本久久中文字幕精品 | 亚洲七七久久精品中文国产 | 成人爱爱爱欧美日本视频 | 最新香蕉97超级碰碰碰碰碰久 | 理论片我不卡在线观看 | 成人午夜天 | 99热免费观看 | 在线观看亚洲免费视频 | 小说区图片区综合久久亚洲 | 一级毛片免费的 | 国产深夜福利视频在线观看 | 香蕉人人超 |