0

I have an Integer array using it as a ByteArray (It is a publicKey) [-33,103,-48,-46,113 .......]

How can I convert it to Blob using Apex?

2
  • 1
    Hi, and welcome to SFSE! Please take a moment to read about How to Ask and take our quick tour. "I hope you are doing well" and "Thank you so much" are not needed in your questions here. Just state plainly what you're trying to do and include as much information as possible. This question may be an X-Y Problem; you might want to edit it to be more specific about what you're doing, what you've tried so far, etc.
    – sfdcfox
    Commented Jul 15, 2022 at 9:33
  • @sfdcfox Thanks for sharing, I'll take the quick tour.
    – Holmes285
    Commented Jul 19, 2022 at 0:41

1 Answer 1

4

Apex doesn't have the notion of "byte arrays", unfortunately, so there's no one-liner that can do this. The best you can do if you start from this array would be something like:

Integer[] values = new Integer[]{-33, 103, -48, -46, 113, ...};
// Buffer
String[] hexValues = new String[0];
// Hex lookup
String[] hex = '0123456789abcdef'.split('');
for(Integer byteValue: values) {
    // Isolate bits 4-7: (240) 0xF0 is the mask
    // Divide by 16 (shift right 4 bits)
    Integer highNybble = (byteValue & 240) >> 4;
    // Isolate bits 0-3 (15) 0x0F is the mask
    Integer lowNybble = byteValue & 15;
    // Write high and low 
    hexValues.add(hex[highNybble]);
    hexValues.add(hex[lowNybble]);
}
Blob result = EncodingUtil.convertFromHex(String.join(hexValues,''));
System.debug(result);

Not terrible, but if you can just take the key's hex output, you get a much more legible:

String publicKeyHex = 'df67d0d271...';
Blob publicKey = EncodingUtil.convertFromHex(publicKeyHex);
1
  • It works perfectly, I see, so hex values are easily converted to Blobs, I'll keep that in mind, Thank you @sfdcfox !
    – Holmes285
    Commented Jul 19, 2022 at 0:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .