ruby将16进制转10进制问题

wuyuanzhe 2010-11-10 08:07:54
有一串16进制字符串,如“01 01 01 01”、“a1 01 b1 01”等

需要将其转成十进制,如“01 01 01 01”---> “1010101” ----> 16843009
“a1 01 b1 01”---> “a101b101” ----> 2701242625

如何操作?
请教各位达人~~~
...全文
444 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyuanzhe 2010-11-12
  • 打赏
  • 举报
回复
看错了
to_i看成to_s了。。。
sorry
helstorm 2010-11-11
  • 打赏
  • 举报
回复
/*
* call-seq:
* str.to_i(base=10) -> integer
*
* Returns the result of interpreting leading characters in <i>str</i> as an
* integer base <i>base</i> (between 2 and 36). Extraneous characters past the
* end of a valid number are ignored. If there is not a valid number at the
* start of <i>str</i>, <code>0</code> is returned. This method never raises an
* exception when <i>base</i> is valid.
*
* "12345".to_i #=> 12345
* "99 red balloons".to_i #=> 99
* "0a".to_i #=> 0
* "0a".to_i(16) #=> 10
* "hello".to_i #=> 0
* "1100101".to_i(2) #=> 101
* "1100101".to_i(8) #=> 294977
* "1100101".to_i(10) #=> 1100101
* "1100101".to_i(16) #=> 17826049
*/
helstorm 2010-11-11
  • 打赏
  • 举报
回复
唉,你至少运行一下再来回帖吧。


/*
* call-seq:
* str.to_i(base=10) -> integer
*
* Returns the result of interpreting leading characters in <i>str</i> as an
* integer base <i>base</i> (between 2 and 36). Extraneous characters past the
* end of a valid number are ignored. If there is not a valid number at the
* start of <i>str</i>, <code>0</code> is returned. This method never raises an
* exception when <i>base</i> is valid.
*
* "12345".to_i #=> 12345
* "99 red balloons".to_i #=> 99
* "0a".to_i #=> 0
* "0a".to_i(16) #=> 10
* "hello".to_i #=> 0
* "1100101".to_i(2) #=> 101
* "1100101".to_i(8) #=> 294977
* "1100101".to_i(10) #=> 1100101
* "1100101".to_i(16) #=> 17826049
*/
wuyuanzhe 2010-11-10
  • 打赏
  • 举报
回复
这个没见有转到10进制的操作啊?
本来就是16进制的,转到最后还是16进制的,基本没用啊
helstorm 2010-11-10
  • 打赏
  • 举报
回复

a = '01 01 01 01' #---> “1010101” ----> 16843009

a.gsub!(/\s/, '')
ia = a.to_i(16)
p ia

b = 'a1 01 b1 01' #---> “a101b101” ----> 2701242625

b.gsub!(/\s/, '')
ib = b.to_i(16)
p ib

2,764

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ruby/Rails
社区管理员
  • Ruby/Rails社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧