Hi,

I looked all over and since I'm probably not using the right termonlogy I couldn't find anything in Google. Here's what I'm trying to do (in ANSI C).
I have a text that represents a series of bytes that looks like this:
"08 FF AB 0B 12 76 CD"

I want to convert each of these "bytes" into REAL binary bytes (is that the right term???). i.e.:
0x08,0xFF,0xAB,0x0B,0x12,0x76,0xCD

I DO NOT want to merely print them that way, but actually STORE them as real binary bytes. So say I read in that first "byte" into a variable:

char * oneByte="08";

Now what? How does this ASCII represntation of "08" become 0x08 (i.e. 0000 1000)?

Thanks
Ami

For the decimal digits you can subtract '0' to get the numeric equivalent:

'0' - '0' = 0
'1' - '0' = 1
'2' - '0' = 2
'3' - '0' = 3
'4' - '0' = 4
'5' - '0' = 5
'6' - '0' = 6
'7' - '0' = 7
'8' - '0' = 8
'9' - '0' = 9

'A' through 'F' are only marginally harder. If you don't mind making an assumption about those characters being contiguous (note that this is guaranteed for the digits, but not anything else), you can just subtract 'A'. A more general solution is something like this:

int digit_value(char ch)
{
    const char *digits = "0123456789ABCDEF";
    size_t i;

    for (i = 0; digits[i]; ++i) {
        if (toupper(ch) == digits[i])
            return i;
    }

    return -1; /* Or any decent "not possible" value */
}

Now you'll have the individual pieces, and it's only a matter of pasting them together. You can use basic arithmetic or bitwise operations, depending on your preference. I'd suggest looking into how atoi() works for further ideas. I'd show you how to do it, but you'll learn more by working a bit. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.