Apex Convert UTF-8->Shift-JIS

public static Blob strToShiftJISBlob (String str){

        String body = '';

        for( Integer i = 0 ; i < str.length(); i++ ){
            String moji = str.substring(i,i+1);

            String encoded = EncodingUtil.urlEncode(moji , 'Windows-31J' );

            if(encoded.length() == 1){
                Integer charval = moji.getChars()[0];
                encoded = '%' + toHex(charval );
            }

            body += encoded;
        }

        body = body.replaceAll('%','');

        Blob blobValue = EncodingUtil.convertFromHex(body);

        return blobValue ;
    }

    private static Map<Integer,String> hexmap = new Map<Integer,String>{
        0  => '0'
       ,1  => '1'
       ,2  => '2'
       ,3  => '3'
       ,4  => '4'
       ,5  => '5'
       ,6  => '6'
       ,7  => '7'
       ,8  => '8'
       ,9  => '9'
       ,10 => 'A'
       ,11 => 'B'
       ,12 => 'C'
       ,13 => 'D'
       ,14 => 'E'
       ,15 => 'F'
    };

    private static String toHex( Integer val ){

    //処理場ありえないが、変換できないものは?
        if(val > 255 ){
            val = '?'.getChars()[0]; 
        }

        Integer moji1 = val / 16;
        Integer moji2 = Math.mod(val , 16);

        return hexmap.get(moji1 ) + hexmap.get(moji2 );
    }

Posted in Apex, Salesforce, Vietnam Offshore on Jan 14, 2019