公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(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

通用课目体育训练成绩评定