How Does Ruby handle bytes/binary?

前端 未结 3 1351
日久生厌
日久生厌 2021-02-05 17:56

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 lan

相关标签:
3条回答
  • 2021-02-05 18:34

    To make a string that has an arbitrary sequence of bytes, do something like this:

    binary_string = "\xE5\xA5\xBD"
    

    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.

    0 讨论(0)
  • 2021-02-05 18:36

    Don't know if this helps enough, but you can index the bits in an integer in ruby.

    n = 0b010101
    
    n # => 21
    
    n = 21
    
    n[0]  # => 1
    n[1]  # => 0
    n[2]  # => 1
    n[3]  # => 0
    n[4]  # => 1
    n[5]  # => 0
    
    0 讨论(0)
  • 2021-02-05 18:52

    Have a look at the String.unpack method. This is an example:

    str = "1010"
    str.unpack("cccc")
    => [49, 48, 49, 48]
    

    This will give you integer values. There are more ways to do the conversion.

    0 讨论(0)
提交回复
热议问题