'How can I decode a hexadecimal to a byte array in Dart?
So there's the 'dart:convert' library, which contains a HexDecoder class that doesn't seem to have a constructor (according to this). But importing it and trying to construct it doesn't work; I thought maybe there was a default constructor not mentioned.
I could copy the code in the source for the convert method, but I'd rather make this a learning opportunity. Any help would be appreciated.
Solution 1:[1]
HexDecoder isn't actually in dart:convert. It's in a package (also) called convert.
You need to add it to your pubspec.yaml and then use an import like:
import 'package:convert/convert.dart';
Then use it like this:
hex.decode('abcdef');
hex is a const singleton instance of the codec. (The constructor is private; you don't need to instantiate your own - use the existing const instance.)
Solution 2:[2]
For anyone who wants to convert hexadecimal numbers to 2's component, Dart has a builtin method .toSigned(int):
var testConversion = 0xC1.toSigned(8);
print("This is the result: " + testConversion.toString()); // prints -63
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard Heap |
| Solution 2 | Elmar |
