所以我试图取一个1和0的字符串并将其转换为十进制等效值,就像字符串是一个字符串一样。我对Java比较熟悉,所以我先用Python编写了这个函数,如下所示。它运作得很好。
def stringToBitString(bs):
#
# bs = "10101"
#
ans = 0 # 32 bits of 0
for bit in bs:
ans = (ans << 1) | (ord(bit) - ord('0'))
return (and)
然而,在尝试将其翻译为Java时,我提出了这个问题。
public int toInt(String path) {
int answer = 0;
for(int i = 0; i < path.length(); i++) {
int bit = path.charAt(i);
answer = (answer << 1) | (bit - 0);
}
return answer;
}
这个方法确实给了我一个int,但是以ASCII的形式。例如stringToBitString(“1”)产生1,而toInt(“1”)产生48.有人可能告诉我此时我做错了吗?
答案 0 :(得分:0)
您正在做的是将'1'
或'0'
减去ASCII值49
和48
减去0
,导致49
或{ {1}}。
48