How to create a hex string from a string

Ref How to convert a float to a string?

For some reason I'm thinking there needs to be no actual conversion, just formatting however I can't seem to grasp the steps.

My goal:
I receive a float from a sensor like 75.3
I need to convert it into a hex ASCII or UTF-8 string

7 = 38
5 = 53
. = 2E
3 = 51

So my string would be "38532E51"

This will be part of the payload for sending data to cluster "Multistate_Value_Basic"
Here is my code for sending my data to this cluster

     def serialdata = "0761626364616125"
    "he raw ${device.deviceNetworkId} 0x01 0x01 0x0014 {104 3 02 0E00 42${serialdata}}"

I started converting the float 78.3 to a string, but I've been unable to convert the string to a hex string.

Thanks.

Don't forget about the HexUtils methods available in Hubitat to make conversions to/from this kind of thing easier:

https://docs2.hubitat.com/en/developer/hexutils-object

So something like HexUtils.byteArrayToHexString(yourString.getBytes("UTF-8")) might work, though you can do pretty much all of this yourself too, as above, if you prefer.

That being said, I'm not sure exactly what device you're dealing with, and I'm not familiar with that cluster, but is the decimal point supposed to be part of this value? This strikes me as unusual, but I suppose it's possible (and certainly so if you have control over both sides and know how to interpret it). But often, you'll have a purely numeric value, and the convention would be that the "real" value is that divided by 10 or something along those lines. Maybe something else to make sure of if you aren't already?

4 Likes

@UserSeventeen , @bertabcd1234

Thank you both. This makes it obvious to me I haven't learned some of the basics. It seems to my mind Groovy is much less cut and dried that C or even VBA.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.