Search code examples
luatorch

how to tackle HEX in torch7?


I'm using async-tcp client to connect to server and receive data(an array).

client.ondata(function(data)
   print('received:',data)
end)

If data type is HEX, I can get data but it is all gibberish.

It seems that there is something wrong with encoding.


If data type is note HEX, I can also get data but it is string.

I have no idea to convert the 'array string' to tensor.

'0.001 0.002 0.003' -> torch.Tensor({{0.001, 0.002, 0.003}}) ??

What should I do ?

Thank you

==================================================

EDIT

string.byte

client.ondata(function(data)
      print('received number:',#data)
      for i = 1, #data do
        print('received:', string.byte(data, i))
      end
end)

Solution

  • If you know the format ahead of time, you can use the match function to get the list of values from a string, which you can then convert to the table and the Tensor:

    local str = "0.001 0.002 0.003"
    torch.Tensor({{str:match("(%d+%.%d*)%s+(%d+%.%d*)%s+(%d+%.%d*)")}})
    

    This returns:

    0.001 *
      1.0000  2.0000  3.0000
    [torch.DoubleTensor of size 1x3]
    

    If the number is in the hex format, you can use tonumber function to convert, for example, tonumber("0x12") == 18.