linux-nvme / nvme-cli

NVMe management command line interface.
https://nvmexpress.org
GNU General Public License v2.0
1.44k stars 647 forks source link

nvme-print-stdout: fix hexadecimal field width #2322

Closed ikegami-t closed 3 months ago

ikegami-t commented 3 months ago

Correct "0x" prepended and zero padded hexadecimal field width. Fixes: 8f61eb4 ("nvme-cli: Add support set feature event in PEL") Fixes: 9b7c76c ("nvme-print-stdout: Add register print functions") Fixes: df11a0e ("nvme-print-stdout: Change hexadecimal value 0x prefix to use %#x")

igaw commented 3 months ago

The # modifier doesn't work on my system correctly for 0. I think we should just go with the old style and prefix our strings ourself. Way to complicated with these additional width strings.

#include <stdio.h>

void test1(unsigned int v)
{
    printf("test0: v %d -> %#0*x\n", v, v ? 4 : 2, v);
}

void test2(unsigned int v)
{
    printf("test1: v %d -> 0x%02x\n", v, v);
}

int main(int argc, char *argv[])
{
    test1(0);
    test1(1);
    test1(300);
    test2(0);
    test2(1);
    test2(300);

    return 0;
}

produces

› ~/tmp/test
test0: v 0 -> 00
test0: v 1 -> 0x01
test0: v 300 -> 0x12c
test1: v 0 -> 0x00
test1: v 1 -> 0x01
test1: v 300 -> 0x12c
ikegami-t commented 3 months ago

Okay let me close the PR changes. By the way about the 0 result is expected behavior as desribed by the man page as below. https://man7.org/linux/man-pages/man3/printf.3.html

#      The value should be converted to an "alternate form". ...
              ...
              For x and X conversions, a nonzero result has the string
              "0x" (or "0X" for X conversions) prepended to it. ...
              ...
igaw commented 3 months ago

Ah, good to know. I thought this is a bug but actually, it is the defined behavior. Not really working for us :(

ikegami-t commented 3 months ago

Thanks for the confirmation.