如何对字符进行2位编码?在Java中 [英] How to encode chars in 2-bits? in java

查看:0
本文介绍了如何对字符进行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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆