Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to write() hexadecimal representation of without any success.

The code I have ft_putstr_non_printable.c:

#include <unistd.h>

void    ft_putstr_non_printable(char *str)
{
    int             i;
    unsigned char   a;
    char            c;

    i = 0;
    a = 0x0;
    while (str[i] != '')
    {
        if (str[i] <= 31 || str[i] == 127)
        {
            a = str[i];
            write(1, &a, 1);
        }
        else
        {
            c = str[i];
            write(1, &c, 1);
        }
        i++;
    }
}

And main.c:

#include <stdio.h>
#include <string.h>

#include "ft_putstr_non_printable.c"

int main(void)
{
    char a[] = "
 au revoira";
    char b[] = "omellette du fromage";
    char c[] = "coeuf@ca6vae fef";
    char d[] = " Batata x7F rfg";
    char e[] = "roquefort`[e{forte-e_tem,bolor 
 feff";
    char f[] = " we 9are 78familly x1F rgfenf";

    ft_putstr_non_printable(a);
    ft_putstr_non_printable(b);
    ft_putstr_non_printable(c);
    ft_putstr_non_printable(d);
    ft_putstr_non_printable(e);
    ft_putstr_non_printable(f);
}

Am I doing something wrong? How do I get x0a?

Edit: I can't use printf(). I'm limited to write().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead writing one character when str[i] is out of the printable range, form a little string and write that.

    // if (str[i] <= 31 || str[i] == 127)
    if (str[i] <= 31 || str[i] >= 127) {
        unsigned char a = str[i];
        char buf[5];
        int len = sprintf(buf, "\x%02X", a);
        // write(1, &a, 1);
        write(1, buf, len);
    }

I'm limited to write()

If sprintf() not available:

        // int len = sprintf(buf, "\x%02X", a);
        buf[0] = '\'; 
        buf[1] = 'x'; 
        buf[2] = "0123456789ABCDEF"[a/16];
        buf[3] = "0123456789ABCDEF"[a%16];
        buf[4] = '';
        len = 4;

Advanced:

char may be unsigned, so values above 127 are possible.

To well reverse the process it might make sense to print the \ in hex.

    if (str[i] <= 31 || str[i] >= 127 || str[i] == '\') {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...