简体   繁体   中英

dereferencing a char pointer

I spent some considerable time on the below example. I will just writing a sample code and noticed it was never giving me the desired output.

Finally it worked but I am not able to explain as to why it happened. The commented lines are those which had the issue. Can someone tell me what I am missing here ?

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

void Ascii2Hex( char* originalByte, unsigned char *ConvertedByte )
{
        while( *originalByte )
        {
                //if( *originalByte >= 48 && *originalByte <= 57 ) 
                if( *(originalByte) >= 48 && *(originalByte) <= 57 )
                        *ConvertedByte = *originalByte - 48;
                //else if( *(originalByte) >= 65 && *(originalByte) <= 70 ) 
                else if( *originalByte >= 65 && *originalByte <= 70 )
                        *ConvertedByte = *originalByte - 55;
                //else if( *originalByte >= 97 && *originalByte <= 102 ) 
                else if( *(originalByte) >= 97 && *(originalByte) <= 102 )
                        *ConvertedByte = *originalByte - 87;
                else
                {       printf( "Not a valid alpha numeric char[%d][%c][%x]\n", *originalByte, *originalByte, *originalByte );
                        ConvertedByte--;
                }
                ConvertedByte++;
                originalByte++;
        }
}

void main()
{
        char *OrigStr = "0123G456A";    
        unsigned char Result[100] = {0};
        int i;

        for( i=0; i<strlen( OrigStr ); i++ )
                printf(" Orig[%02x][%c]\n", OrigStr[i], OrigStr[i] );
        Ascii2Hex( OrigStr, Result );
        for( i=0; i<strlen( OrigStr ); i++ )
                printf(" Result[%02X]\n", Result[i] );
}

You are decoding each hexadecimal digit into a byte. Bytes of eight bits are represented by two hexdigits.

Regarding the magic numbers: What is 48 or 65 standing for? Not everyone remembers the ASCII codes. Just write '0' or 'A'.

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