Busybox awk: how to treat each character in a String as an integer to perform bitwise operations?

I want to change the SSID name of the wifi network dynamically in OpenWRT through a script that grab information from the internet.

Since the information grabbed from the internet can be multiple bytes of characters, so it can be easily truncated to an invalid UTF-8 byte sequence, so I want to use awk (busybox) to fix it. However, when I try to use the bitwise function and

for string and integer, the result always returns 0

.

awk 'BEGIN{v="a"; print and(v,0xC0)}'

      

How to handle character in String as integer in awk, how can we do in C / C ++? char p[]="abc"; printf ("%d",*(p+1) & 0xC0);

+3


source to share


2 answers


You can create your own function ord

like this - borrowed heavily from the GNU Awk User's Guide - here

#!/bin/bash

awk '
BEGIN    {  _ord_init() 
            printf("ord(a) = %d\n", ord("a"))
         }

function _ord_init(    low, high, i, t)
{
    low = sprintf("%c", 7) # BEL is ascii 7
    if (low == "\a") {    # regular ascii
        low = 0
        high = 127
    } else if (sprintf("%c", 128 + 7) == "\a") {
        # ascii, mark parity
        low = 128
        high = 255
    } else {        # ebcdic(!)
        low = 0
        high = 255
    }

    for (i = low; i <= high; i++) {
        t = sprintf("%c", i)
        _ord_[t] = i
    }
}

function ord(str,c)
{
    # only first character is of interest
    c = substr(str, 1, 1)
    return _ord_[c]
}'

      



Output

ord(a) = 97

      

+2


source


I don't know if this is what you mean, since you didn't provide a sample input and expected output, but look at it with GNU awk and maybe it helps:



$ gawk -lordchr 'BEGIN{v="a"; print v " -> " ord(v) " -> " chr(ord(v))}'
a -> 97 -> a

      

0


source







All Articles