Convert image to Ascii hexadecimal code in Net Core


Audience
Tags

Hi. I currently have a problem converting an image to hex code to be displayed in the ZPL code. I've tried many code snippets to no avail

public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
for (int i = 0; i < ba.Length; i++) // <-- Use for loop is faster than foreach
hex.Append(ba[i].ToString("X2")); // <-- ToString is faster than AppendFormat
return hex.ToString();
}

I am using Net Core 3.1
Any idea how to convert the image?

Submitted by James Swinton … on May 24, 2022 Permalink

Hi,

Maybe you could try this method

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
    }
    return new String(hexChars);
}

Thanks,

James