Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

Dart Convert from base64 to HEX

I don't know how to convert this base64 String:

'g7DmoaMppUjtbxe5Qm9NlMr5pRitu7TayInEUMeOW+FDxYW3GAh+G0YsfmoAyfqTw72fWphF9ncT
P7QnsXAM8Of6o92AuVzryBt5Usm4sJ32GLaH+9SNx3J5DK1NjKrWSbP0F/EyrGjoveBc2Ut7XntM
p8NcGn39eD+PHQKfWnc='

to this HEX:

'83b0e6a1a329a548ed6f17b9426f4d94caf9a518adbbb4dac889c450c78e5be143c585b718087e1b462c7e6a00c9fa93c3bd9f5a9845f677133fb427b1700cf0e7faa3dd80b95cebc81b7952c9b8b09df618b687fbd48dc772790cad4d8caad649b3f417f132ac68e8bde05cd94b7b5e7b4ca7c35c1a7dfd783f8f1d029f5a77'

I used this link to convert it https://base64.guru/converter/decode/hex

question from:https://stackoverflow.com/questions/65870613/dart-convert-from-base64-to-hex

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this should do the trick:

import 'dart:convert';

void main() {
  final hex = base64Decode(
          'g7DmoaMppUjtbxe5Qm9NlMr5pRitu7TayInEUMeOW+FDxYW3GAh+G0YsfmoAyfqTw72fWphF9ncT'
          'P7QnsXAM8Of6o92AuVzryBt5Usm4sJ32GLaH+9SNx3J5DK1NjKrWSbP0F/EyrGjoveBc2Ut7XntM'
          'p8NcGn39eD+PHQKfWnc=')
      .map((e) => e.toRadixString(16).padLeft(2, '0'))
      .join();

  print(hex);
  // 83b0e6a1a329a548ed6f17b9426f4d94caf9a518adbbb4dac889c450c78e5be143c585b718087e1b462c7e6a00c9fa93c3bd9f5a9845f677133fb427b1700cf0e7faa3dd80b95cebc81b7952c9b8b09df618b687fbd48dc772790cad4d8caad649b3f417f132ac68e8bde05cd94b7b5e7b4ca7c35c1a7dfd783f8f1d029f5a77
}

Updated solution which handles newlines in input:

import 'dart:convert';

void main() {
  print(base64ToHex(
      'g7DmoaMppUjtbxe5Qm9NlMr5pRitu7TayInEUMeOW+FDxYW3GAh+G0YsfmoAyfqTw72fWphF9ncT
'
      'P7QnsXAM8Of6o92AuVzryBt5Usm4sJ32GLaH+9SNx3J5DK1NjKrWSbP0F/EyrGjoveBc2Ut7XntM
'
      'p8NcGn39eD+PHQKfWnc='));
  
  // 83b0e6a1a329a548ed6f17b9426f4d94caf9a518adbbb4dac889c450c78e5be143c585b718087e1b462c7e6a00c9fa93c3bd9f5a9845f677133fb427b1700cf0e7faa3dd80b95cebc81b7952c9b8b09df618b687fbd48dc772790cad4d8caad649b3f417f132ac68e8bde05cd94b7b5e7b4ca7c35c1a7dfd783f8f1d029f5a77
}

String base64ToHex(String source) =>
    base64Decode(LineSplitter.split(source).join())
        .map((e) => e.toRadixString(16).padLeft(2, '0'))
        .join();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...