请问如何处理红宝石字节/二进制? [英] How Does Ruby handle bytes/binary?
问题描述
我想跨越套接字发送一串二进制字节,以满足特定的标准我公司使用。没有人在我公司以前使用Ruby的这一点,但在其他语言中,他们跨越一个字节发送数据的时间,(通常带有某种打包的方法)。
I'm trying to send a series of binary bytes across a socket, to meet a particular standard my company uses. No one in my company has used Ruby for this before, but in other languages, they send the data across one byte at a time, (usually with some sort of "pack" method).
我找不到反正即时创建二进制,或者创建在所有字节(最接近我能找到它,你可以怎样把字符串转换成字节重新presenting它的字符)。
I can't find anyway to create binary on the fly, or create bytes at all (the closest I can find it how you can turn a string into the bytes representing it's characters).
我知道你可以这样说:
@var = 0b101010101
@var = 0b101010101
不过,我将如何转换成字符串的形式为101010101,或当我做string.to_i(2)转换为实际的二进制创建的结果的整数。如果我只是发送字符串翻过一个插座,将不只是为发送0和1,而不是文字字符的ASCII码?
But how would I convert a string in the form "101010101" or the resulting integer created when I do string.to_i(2) into an actual binary. If I just send the string accross a socket, won't that just send the ASCII for "0" and "1" instead of the literal characters?
当然,有一些方法来做到这一点本身在Ruby中?
Surely there is SOME way to do this natively in Ruby?
推荐答案
要做出一个具有字节任意序列的字符串,做这样的事情:
To make a string that has an arbitrary sequence of bytes, do something like this:
binary_string = "\xE5\xA5\xBD"
在\\ x是一个特殊的逃生EN code从十六进制任意字节,所以\\ xE5是指字节为0xE5。
The "\x" is a special escape to encode an arbitrary byte from hex, so "\xE5" means byte 0xE5.
然后尝试发送套接字上该字符串。
Then try sending that string on the socket.
这篇关于请问如何处理红宝石字节/二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!