简体   繁体   中英

Scanf unsigned char in hex

I am trying to change data in array, this is part of my code:

u_char paket[100];
//here i put some data into array and then trying to change it by user
scanf("%hhx.%hhx.%hhx.%hhx.%hhx.%hhx", &paket[0], &paket[1], &paket[2], &paket[3], &paket[4], &paket[5]);

When my input is for example 88.88.88.88.88.88 it sets paket[0] - paket[5] to 88, but it also changes paket[6], paket[7] and paket[8] to 0.

How is it possible and how to fix it please? I need to change only [0] - [5]

Your code is correct for C99 and later. Presumably you are using a C standard library that does not support the hh length modifier, which was introduced in C99; probably the Microsoft C standard library.

If you need to support this old C standard library, you will have to rewrite your code to be C89-compatible, for example:

unsigned p[6];

if (scanf("%x.%x.%x.%x.%x.%x", &p[0], &p[1], &p[2], &p[3], &p[4], &p[5]) == 6)
{
    int i;
    for (i = 0; i < 6; i++)
        paket[i] = p[i];
}

Your code is fine

u_char paket[100];
scanf("%hhx.%hhx.%hhx.%hhx.%hhx.%hhx", &paket[0], &paket[1], &paket[2], &paket[3], &paket[4], &paket[5])

Does not change the values of paket[6], paket[7] and paket[8] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM