简体   繁体   中英

How to char[] to Hex? C

So I have kind of hit a road block in my project. What I am trying to do is figure out a way to take four individual binary characters which are representing flags. Now my last task was to take these four flags and put them in a char[] which wasn't difficult at all. But now, I want to take the four and convert it to a hex.

So for example:

O = 1;
C = 1;
Z = 0;
N = 0;

char flags[5];
flags[0] = O;
flags[1] = C;
flags[2] = Z;
flags[3] = N;

Now I wanted to make a string or something i can convert the above to a Hex. So for example I want to have 1100 converted to a hex which is 0xC

Now I have tried to make it in to a string first then parse it but I'm confused and lost now. I just can't see to get the right output.

int flags;
flags = (O << 3) | (C << 2) | (Z << 1) | N;
sprintf(buffer, "0x%02X", 0xff & flags);

flags is defined a single int -variable containing all your flags.

buffer is a char array of sufficient size.

The 0xff & .. is not needed in this case, but might be some day if your flags variable can get negative and you still only want to have a one byte output (2 hex digits).

unsigned char flags = 0; flags = ((O << 3) | (C << 2) | (Z << 1) | N);

now flag contains the Hex value you need.

put flags[4]="\\0"

we can have a new variable-char pointer pointing to this array of characters.

then you can use sprintf(newArray[i], "%x", flags[i]);

this will generate each character into HEX in newArray string, we can get the output by printing the string. printf("%s\\n",newArray);

You can use this code for convert a byte[] to hex string

Cast your char[] into byte[] or modify the code as you need :)

    /// <summary>
    /// Converts a byte array to a hex string. For example: {10,11} = "0A 0B"
    /// </summary>
    public static string ByteToHex(byte[] data)
    {
        StringBuilder sb = new StringBuilder();

        foreach (byte b in data)
        {
            string hex = ByteToHex(b);
            sb.Append(hex);
            sb.Append(" ");
        }

        if (sb.Length > 0)
            sb.Remove(sb.Length - 1, 1);

        return sb.ToString();
    }

    /// <summary>
    /// Converts the byte to a hex string. For example: "10" = "0A";
    /// </summary>
    public static string ByteToHex(byte b)
    {
        string sB = b.ToString(ConstantReadOnly.HexStringFormat, CultureInfo.InvariantCulture);

        if (sB.Length == 1)
            sB = "0" + sB;

        return sB;
    }

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