help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Help fixing NativeMessaging host: read 32-bit message length in nati


From: Grisha Levit
Subject: Re: Help fixing NativeMessaging host: read 32-bit message length in native byte order
Date: Sat, 24 Jun 2023 20:39:18 -0400

On Sat, Jun 24, 2023, 10:02 Greg Wooledge <greg@wooledge.org> wrote:

> Reading that 4-byte binary number value is the hard part
>

I think it's doable alright if you read one byte at a time with:
* LC_ALL=C
* read -r -d '' -n 1
* either set a null IFS value or using `read' without supplying an explicit
variable name

You can then convert the single character of input to a decimal value with
printf's %d conversion specifier and an argument consisting of a quote
character followed by the character.

If a null byte is read there's no problem because:
* read -d '' will return 0 and set an empty REPLY
* printf %d "'" outputs 0


LC_ALL=C
readmsg() {
    # return non-zero if fewer than 4 bytes of input available or if message
    # is shorter than length specified by first 4 bytes of input
    # otherwise, set $msg and return 0

    local -i i n len=0
    for ((i=0; i<4; i++)); do
        read -r -d '' -n 1 || return
        printf -v n %d "'$REPLY"
        len+='n<<i*8'
    done
    read -r -N "$len" && ((${#REPLY}==len)) && msg=$REPLY
}

sendmsg() {
    local x
    printf -v x %08X "${#1}"
    printf %b%s "\x${x:6:2}\x${x:4:2}\x${x:2:2}\x${x:0:2}" "$1"
}


reply via email to

[Prev in Thread] Current Thread [Next in Thread]