首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python -将字符转换为Bitstring

Python -将字符转换为Bitstring
EN

Stack Overflow用户
提问于 2019-03-15 17:58:51
回答 1查看 71关注 0票数 1

这是一个家庭作业,但我已经把工作放在我的解决方案,不知道我是从哪里得到一个错误。以下是我应该做的事:

  1. 向每个字符的数字ASCII值中添加1。
  2. 将其转换为位字符串。
  3. 将字符串的位移到左边一处。

下面是我到目前为止掌握的代码:

代码语言:javascript
复制
message = input("Enter a message: ")
ordstore = 0

for ch in message:
    ordstore = ord(ch) + 1
    bstring = ""
    while ordstore > 0:
        remainder = ordstore % 2
        ordstore = ordstore // 2
        bstring = str(remainder) + bstring

#print(bstring)

if(len(bstring) > 0):
    move1 = bstring[0]
    new_string = bstring[1:]
    new_string += move1

print(new_string)

我的问题是,我正在覆盖存储在第一个for循环中的值。我最初的想法是用:

代码语言:javascript
复制
ordstore = ord(ch) += 1

然而,这也不能解决我的问题。

任何帮助或指导都是非常感谢的!

EN

回答 1

Stack Overflow用户

发布于 2019-03-15 18:22:21

我建议在第二个循环中使用一个临时变量,这样就可以将其拆分,而不是使用ordstore变量。

代码语言:javascript
复制
for ch in message:
    ordstore = ord(ch) + 1
    bstring = ""
    tempordstore = ordstore 
    while tempordstore > 0:
        remainder = tempordstore % 2
        tempordstore = tempordstore // 2
        bstring = str(remainder) + bstring

但是即使在这里,您的bstring也会被替换为每个ch in message。也许把它带到外面,这样你就可以继续添加到bstring中了

代码语言:javascript
复制
bstring = ""
for ch in message:
    ordstore = ord(ch) + 1
    tempordstore = ordstore 
    while tempordstore > 0:
        remainder = tempordstore % 2
        tempordstore = tempordstore // 2
        bstring = str(remainder) + bstring

这样,您的bstring就不仅仅是基于消息的最终特征。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55188351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档