KEEP K.I.S.S.

tk's blog

Ruby的字节操作

tk posted @ Dec 17, 2011 06:34:10 PM in Ruby with tags ruby 脚本 , 2944 阅读

一个字节其实也就是一个整数,如果用十六进制表示的话,正好是两个十六进制数,用字符串表示就是 “HH”这样的表示。

Ruby的字节操作主要是靠两个方法来实现,String#unpack 和 Array#pack,两个类的实例方法,参数均为单一字符串。

举一个例子来讲解。

一般的 32位 Little-endian 机器上的单精度浮点数 float的一个实例: f = 88.888,得到它的字节表示 =>

因为字节操作需要 Array 类的 pack 操作,所以先把 f 放入一个数组实例中

 

irb(main):001:0> f = 88.888
=> 88.888
irb(main):002:0> s = []
=> []
irb(main):003:0> s << f
=> [88.888]
irb(main):004:0>

然后需要 pack 得到字符串表示

 

irb(main):004:0> s.pack("F")
=> "\xA8\xC6\xB1B"

也许会奇怪这个字符串为什么会这样,其实这里是 "\xA8\xC6\B1\x42",因为 \x42 正好是ASCII码表中 'B' 的十六进制代码,所以这里会显示成这样连着的。

然后我们得到字节的数值表示和十六进制表示:

 

irb(main):005:0> s.pack("F").unpack("C*")
=> [168, 198, 177, 66]
irb(main):006:0> s.pack("F").unpack("H*")
=> ["a8c6b142"]

还有一种方式:

 

irb(main):007:0> s.pack("F").unpack("C*").collect {|x| x.to_s(16) }
=> ["a8", "c6", "b1", "42"]

其实难点在于 pack 和 unpack 的操作,这个参数会很多,理解起来也有点难度,我觉得还是多用用就比较好理解了。

smart air purifiers 说:
Feb 17, 2023 09:02:27 PM

I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read !! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site. smart air purifiers

Крымские Мальдивы 说:
Feb 23, 2023 11:51:29 PM

НОВЫЙ ОТЕЛЬ Мы хотим стать вашим любимым местом отдыха в Крыму, поэтому всегда будем стараться наполнить ваше пребывание здесь заботой и комфортом. Отель в Крыму

clenbuterol for sale 说:
Mar 09, 2023 10:37:15 PM

Hi there, I found your blog via Google while searching for such kinda informative post and your post looks very interesting for me clenbuterol for sale

Отдых в Крыму 说:
Mar 23, 2023 08:03:25 PM

НОВЫЙ ОТЕЛЬ Мы хотим стать вашим любимым местом отдыха в Крыму, поэтому всегда будем стараться наполнить ваше пребывание здесь заботой и комфортом. Отель в Крыму

cannabis phuket 说:
Jul 01, 2023 09:41:14 AM

As a seller of legal steroids, you can buy Crazy Bulk products, explore stacks and finally get the body you’ve always wanted cannabis phuket

does chime have a ro 说:
Jul 23, 2023 02:33:02 AM

If your looking for Online Illinois license plate sticker renewals then you have need to come to the right place.We offer the fastest Illinois license plate sticker renewals in the state. does chime have a routing number

singapore best 说:
Jul 26, 2023 09:27:43 PM

Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work! singapore best

Which Bank Swift Cod 说:
Jul 26, 2023 09:43:41 PM

Chase SWIFT code is Chasus33. It specifies your responder's bank, branch, and country. Your wire transfer may fail without that. Which Bank Swift Code Is Chasus33?

TX Solar 说:
Jul 30, 2023 04:58:23 AM

Guarantee your photovoltaic panel variety is large enough to run your house. You can have a grid-connected system or an off-grid solar panel system. TX Solar

orchard yoga studio 说:
Aug 01, 2023 10:38:27 PM

I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job ! orchard yoga studio

베트남 밤문화 说:
Aug 01, 2023 10:53:13 PM

I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read !! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site. 베트남 밤문화

house cleaning 说:
Aug 01, 2023 11:23:34 PM

With so many books and articles coming up to give gateway to make-money-online field and confusing reader even more on the actual way of earning money, house cleaning

https://rockwalltexa 说:
Aug 04, 2023 05:00:37 AM

Very informative post ! There is a lot of information here that can help any business get started with a successful social networking campaign ! https://rockwalltexas.us/directory/

먹튀검증 说:
Aug 17, 2023 04:50:52 AM

It is perfect time to make some plans for the future and it is time to be happy. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it! 먹튀검증

Real Estate Broker 说:
Aug 20, 2023 04:28:43 AM

Writing with style and getting good compliments on the article is quite hard, to be honest.But you've done it so calmly and with so cool feeling and you've nailed the job. This article is possessed with style and I am giving good compliment. Best! Real Estate Broker

Mark Roemer Real Est 说:
Aug 23, 2023 09:51:30 AM

I see some amazingly important and kept up to length of your strength searching for in your on the site Mark Roemer Real Estate Agent

Tishman Speyer Real 说:
Aug 23, 2023 12:53:14 PM

I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you. Tishman Speyer Real Estate Broker

iptv 说:
Aug 25, 2023 08:37:30 AM

I have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon… iptv

Best Restaurant Cafe 说:
Dec 07, 2023 11:14:49 AM

I will really appreciate the writer's choice for choosing this excellent article appropriate to my matter.Here is deep description about the article matter which helped me more.

amarnath helicopter 说:
Jul 21, 2024 09:14:38 AM

very interesting post.this is my first time visit here.i found so many interesting stuff in your blog especially its discussion..thanks for the post!


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter