将十六进制字符转换为一串位(Python或Ruby) [英] Convert Hex Chars into a String of Bits (Python or Ruby)

查看:106
本文介绍了将十六进制字符转换为一串位(Python或Ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个微控制器从HTTP API返回类似这样的状态响应:

 < response>< BS> ; 026219AAF80F440206025019AAF816A944274480< / BS>< /响应> 

最后两个字符,在这种情况下 80 代表一个十六进制值,我需要将它转换为二进制位 10000000 。每一位都是一个标志,对应于该硬件上的一个状态。



对于我来检查8位中的每一位,我需要取 80 (整个响应是一个字符串,我只抓取最后2个字符),并将其转换为二进制 10000000 所以我可以单独检查8个字符中的每一个。



最好的方法是什么?我想用Python或Ruby来做,但我很乐意学习我期望做的一般技巧,然后弄清楚。



注意:我(显然)没有CS背景,这对我来说很陌生。我可能会使用错误的术语。请随时纠正我;

在Ruby中:

  yourbits =026219AAF80F440206025019AAF816A944274480[ -  2,2] .to_i(16).to_s(2)
=> 10000000
把yourbits
10000000
=> nil

解释每个步骤 - 首先,切分字符串以获取最后2个字符:

 026219AAF80F440206025019AAF816A944274480[ -  2,2] 
=> '80'

将其转换为整数:

 80.to_i(16)
=> 128

返回字符串againg,用二进制表示:

  128.to_s(2)
=> '10000000'

这样做可能更好(或者更少混淆),但我可以'现在想象它。


I have a microcontroller that returns a status response like this from an HTTP API:

<response><BS>026219AAF80F440206025019AAF816A944274480</BS></response>

The last two characters, in this case 80, represent a hexadecimal value that I need to convert to a its binary bits 10000000. Each bit is a flag that corresponds to a state on that piece of hardware.

For me to inspect each of the 8 bits, I need to take the string 80 (the whole response is a string and I just grab the last 2 characters) and turn it into a string representation of the binary 10000000 so I can inspect each of the 8 characters individually.

What's the best way to go about this? I'd like to do it in Python or Ruby, but I'm happy to learn the general technique of what I'm looking to do and then figure it out.

Note: I (obviously) don't have a CS background so much of this is foreign to me. I might be using the wrong nomenclature. Please feel free to correct me; I hope I got out the gist of what I'm looking for.

解决方案

In Ruby:

yourbits = "026219AAF80F440206025019AAF816A944274480"[-2,2].to_i(16).to_s(2)
=> "10000000"
puts yourbits
10000000
=> nil

Explaining each step -- first, slice the string to get the last 2 characters:

"026219AAF80F440206025019AAF816A944274480"[-2,2]
=> '80'

Convert it to Integer:

"80".to_i(16)
=> 128

Back to string againg, in a binary representation:

128.to_s(2)
=> '10000000'

There's probably a better (or less confusing) way of doing it, but I can't imagine it right now.

这篇关于将十六进制字符转换为一串位(Python或Ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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