gpt4 book ai didi

java - DNA 文件转换的位操作

转载 作者:行者123 更新时间:2023-11-29 05:24:01 24 4
gpt4 key购买 nike

我正在用 Scala 构建一个程序,该程序将使用每个字符 8 位的 txt 文件中存储的 DNA 数据转换为使用每个字符 2 位的文件。 DNA 使用的唯一字符是 T、C、A、G。我想为每个字符使用 2 位,其中 T = 00、C = 01、A = 10 和 G = 11。我希望它尽可能紧凑,没有任何浪费的位。

现在,我正在为每个字符写出 8 位,而不是我想使用的两个。对于 outPut 方法,您能否建议我可以执行任何位操作以最大化空间并且每个字符仅使用两位?

最佳答案

一次输出少于一个字节是不可能的。在写出一个字符之前,您必须从 2 位 dna 字母构建一个 8 位字符。

我不知道 Scala 或 Java,但结合您的代码和更像 C 的代码,它会像这样:

  def outPut(in: DataInputStream, out: DataOutputStream) {
var result = getChars(in)

int letter_count = 0 // whatever a plain old integer is called
char byte = 0

for(i <- 0 until result.length) {

if (result(i) == "A") {
byte = (byte << 2) | 2 // move byte over 2 bits and "or" in new bits
}else if(result(i) == "T") {
byte = (byte << 2) | 0 // the "| 0" part here actually does nothing
}else if(result(i) == "C") {
byte = (byte << 2) | 1
}else {
byte = (byte << 2) | 3
}

letter_count += 1

if (letter_count == 4) {
out.writeByte(byte)
letter_count = 0
byte = 0
}

}
}

同时注意 user3580294 的回答。

从另一个方向(从 2 位编码到字符编码):

  def toLetter(x) {
if (x == 0)
return "T"
else if (x == 1)
return "C"
else if (x == 2)
return "A"
else if (x == 3)
return "G"
}

def outputLetters(in: DataInputStream, out: DataOutputStream) {
var twobit = getChars(in) // or however you read the file

for(i <- 0 until twobit.length) {
byte = twobit(i)
out.writeByte(toLetter((byte >> 6) & 3))
out.writeByte(toLetter((byte >> 4) & 3))
out.writeByte(toLetter((byte >> 2) & 3))
out.writeByte(toLetter( byte & 3))
}
}

这基本上假设字母的数量可以被 4 整除。要克服这个限制,您需要在文件中存储一条额外的信息。它可以是最后一个字节中的字母数(1 到 4),也可以是文件中表示的字母总数(从中可以计算出最后一个字节中的字母数)。

关于java - DNA 文件转换的位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com