Search code examples
groovy

Groovy reverse() to reverse a string throws error


Wanted to represent the version which is in big Endian in this format 'B.2.00.4C' but I came up with the below snippet in groovy

def version = '4C00020B'
byte[] byteVersion = version.decodeHex()
byte[] byteReversed = byteVersion.reverse()
def versionStr = byteReversed.collect { String.format('%02X', it) }.join('.')
println versionStr

which throws below error.

groovy.lang.MissingMethodException: No signature of method: [B.reverse() is applicable for argument types: () values: []
Possible solutions: every(), every(groovy.lang.Closure) at Script1.run(Script1.groovy:3)

Also my solution doesn't remove zero if there's a non zero value in each byte exists. How can I fix the error and get the output in the format I wanted?


Solution

  • There's no reverse method on arrays, you'll need to convert it to a list

    byte[] byteReversed = byteVersion.toList().reverse()
    

    Then, to get the format you want, you'll need to drop the 02 from the formatting, but handle 0 separately

    def versionStr = byteReversed.collect { 
        it == 0 ? '00' : String.format('%X', it) 
    }.join('.')