日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

本文介紹了如何對字符進行2位編碼?在Java中的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

DNA分子由以下四個值之一表示:A、C、G或T。我需要將A、C、G和T中的字符串轉換為對每個字符進行編碼的字節數組
有兩個比特。A比特00,C比特01,G比特10,T比特11。我不知道如何將字符轉換為2比特。我試著改變和掩飾,但得到了錯誤的結果。
在開始時,我檢查該行中是否有字符。然后,我將每個字符轉換為位值并將其插入到數組中。當我插入ACGT時,我在輸出中得到0 1 3 2。在這里我遇到了一個問題,因為我不知道如何將值轉換為2位。

Scanner text = new Scanner(System.in);
String str = text.nextLine();

if (str.contains("A") && str.contains("C") && str.contains("G") && str.contains("T")){
  System.out.println("");
}
else
{
  System.out.println("wrong command format");
} 

byte mas[] = str.getBytes();
System.out.println("String in byte array : " + Arrays.toString(mas));

for (int i = 0; i < mas.length; i++){
  byte mask = 3;
  byte number = mas[i];
  byte result = (byte)((number >> 1) & mask); 
  System.out.println(result);
}
}

}

推薦答案

您似乎想要將位保存在一個字節中。下面的例子可能會給出一些啟示。

public class Main
{
    private static final int A = 0x00; // b00
    private static final int C = 0x01; // b01
    private static final int G = 0x02; // b10
    private static final int T = 0x03; // b11
    
    public static void main(String[] args) throws Exception
    {   
        byte store = 0;
        store = setByte(store, 0, A);
        store = setByte(store, 1, C);
        store = setByte(store, 2, G);
        store = setByte(store, 3, T);
        System.out.println(Integer.toBinaryString(store));
        //11111111111111111111111111100100
        System.out.println(getByte(store, 0)); //0
        System.out.println(getByte(store, 1)); //1
        System.out.println(getByte(store, 2)); //2
        System.out.println(getByte(store, 3)); //3
    }
    
    //Behavior :: Store "value" into "store".
    //Reminder :: Valid index 0 - 3. Valid value 0 - 3.
    private static byte setByte(byte store, int index, int value)
    {   
        store = (byte)(store & ~(0x3 << (2 * index)));
        return store |= (value & 0x3) << (2 * index);
    }

    private static byte getByte(byte store, int index)
    {
        return (byte)((store >> (2 * index)) & 0x3);
    }
}

這篇關于如何對字符進行2位編碼?在Java中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,

分享到:
標簽:Java 字符 編碼
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定