WilliamVenner / vscode-glua-enhanced

👨‍💻 Garry's Mod Lua VSCode Extension for enhanced auto completion, wiki integration, snippets, color palette, and much more...
https://marketplace.visualstudio.com/items?itemName=venner.vscode-glua-enhanced
GNU General Public License v3.0
410 stars 10 forks source link

'decode' hex strings #12

Closed Yogpod closed 3 years ago

Yogpod commented 3 years ago

https://cdn.discordapp.com/attachments/565108080300261398/808074657831583805/Cojqh00q2C.gif

local CharacterForEscape = {
    ["b"] = "\b",
    ["x"] = true,
    ["f"] = "\f",
    ["v"] = "\v",
    ["0"] = "\0",
    ["r"] = "\r",
    ["n"] = "\n",
    ["t"] = "\t",
    ["\""] = "\"",
    ["'"] = "\"",
    ["\\"] = "\\"
}

local function tohex(str)
    return str:gsub(".", function(c) return string.format("%02X", string.byte(c)) end)
end

local function StringToHex(str)
    local function peek(n)
        return string.sub(str, n, n) or "N/A"
    end

    local hex, skips = "", 0

    for i = 1, #str do
        if peek(i) == "\\" then
            if isnumber(tonumber(peek(i + 1))) then
                skips = skips + 1

                for v = 1, 2 do
                    if isnumber(tonumber(peek(i + 1 + v))) then
                        skips = skips + 1
                    end
                end

                hex = hex .. "\\"
                continue
            elseif peek(i + 1) == "x" then
                skips = skips + 3
                hex = hex .. "\\"
                continue
            elseif CharacterForEscape[peek(i + 1)] then
                skips = skips + 1
                hex = hex .. "\\"
                continue
            end
        end

        if skips > 0 then
            skips = skips - 1
            hex = hex .. peek(i)
            continue
        end

        hex = hex .. "\\x" .. tohex(peek(i))
    end

    return hex
end

print(StringToHex("bruh")) --\x62\x72\x75\x68

probably a better way to get hex strings but that's one way