Hex String to Image

前端 未结 2 1127
梦谈多话
梦谈多话 2021-01-25 14:52

I have a hex string which looks like:

String hexImage =\"0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C...\"

Whi

2条回答
  •  后悔当初
    2021-01-25 15:07

    Normally, each byte is represented by 2 hex digits, therefore, if you have an odd number of digits in your HEX string, then something is wrong with it. You can try padding it with 0 in the beginning, such as this:

    String hexImage ="0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C...";
    if(hexImage.length()%2 == 1)
        hexImage = "0x0" + hexImage.substring(2);
    

    or at the end, such as this:

    String hexImage ="0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C...";
    if(hexImage.length()%2 == 1)
        hexImage += "0";
    

    However this is not guaranteed to produce a proper image.

    On the whole, you should check how you get your hex string. A proper byte sequence should always contain an even number of hex digits.

    EDIT: In addition, as Peter Lawrey indicated in his comment, you should check whether the decode method expects 0x in front of the string.

提交回复
热议问题