hex value (0x21AF) set in ByteData in dart flutter - flutter

var i=23FF;
how to convert this
convert i value in hex value like 0x23FF
ByteData mssg = ByteData(12);
mssg.setUint16(5, 0x23FF);
How I set hex value in ByteData
Thankyou

final hexString = myInteger.toRadixString(16); // 7e4
Convert it into String and count the number of places.
final paddedString = hexString.padLeft(count, '0x'); // 0x7e4
Decimal to Hex
String hex = 2020.toRadixString(16).padLeft(4, '0');
print(hex); // 07e4
Decimal to Binary (ByteData)
String binary = 2020.toRadixString(2);
print(binary); // 11111100100
Hex to Binary (ByteData)
String binary = hex.toRadixString(2);
print(binary); // 11111100100

Related

Convert double value to List<Int> in Dart

I'm using flutter_blue to communicate with a bluetooth device. I need to pass a double value to the bluetooth device using the flutter_blue write() method.
The value must be passed to the method as a list of integers which is supposed to represent a list of bytes as far as i understand it.
The flutter_blue write method:
Future<Null> write(
List<int> value,
{bool withoutResponse = false}
)
Is there a way to convert a double value to a list of integers that represents the double value as a list of bytes in order to pass it to flutter_blues write method?
For example:
double value = 10.52;
List<Int> convertedValue = someConversionMethod(value);
await bluetoothCharacteristic.write(convertedValue);
With Bluetooth it is normal to pass information as a list of bytes(Uint8List). The solution for float value is to have an expected exponent. There is more detail in the GATT Specification Supplement 4 especially in section 2 "Values and represented values"
If the number is large enough it will need to be converted to bytes in little endian format. As an example:
import 'dart:typed_data';
import 'dart:math';
void main() {
double value = 10.52;
var rawValue = value * pow(10, 2); // multiply value to remove decimal places
print('Raw value to send: $rawValue'); // Raw value to send 1052
var sendValue = ByteData(2);
sendValue.setUint16(0, rawValue.toInt(), Endian.little);
print('As Uint8List of values: ${sendValue.buffer.asUint8List()}');
// As Uint8List of values: [28, 4]
}
The dart:typed_data library has some useful methods to convert data to bytes. This method worked for me.
import 'dart:typed_data';
List<int> doubleToListInt(double value) {
ByteData bytes = ByteData(8);
bytes.setFloat64(0, value);
List<int> response =
bytes.buffer.asInt8List().toList();
return response;
}
print(doubleToListInt(10.52)); // Returns [64, 37, 10, 61, 112, -93, -41, 10]

How to convert a binary string to text string and the reverse in flutter?

What I wanna do is to input a string like ["01001000 01100101 01111001"] and convert it to ["Hey"] or the opposite too, input ["Hey"] and convert it to ["01001000 01100101 01111001"]
String encode(String value) {
// Map each code unit from the given value to a base-2 representation of this
// code unit, adding zeroes to the left until the string has length 8, and join
// each code unit representation to a single string using spaces
return value.codeUnits.map((v) => v.toRadixString(2).padLeft(8, '0')).join(" ");
}
String decode(String value) {
// Split the given value on spaces, parse each base-2 representation string to
// an integer and return a new string from the corresponding code units
return String.fromCharCodes(value.split(" ").map((v) => int.parse(v, radix: 2)));
}
void main() {
print(encode("Hey")); // Output: 01001000 01100101 01111001
print(decode("01001000 01100101 01111001")); // Output: Hey
}

Base64 string reduces after putting Map (data structure) into json.decode(map)

I am converting an Image to base64 and then I am putting it into the Map data structure, but when I convert Map into the JSON string, base64 string reduces and gets the reduced length response from the server. My question is why is Map reducing it?
"Message": "Invalid length for a Base-64 char array or string."
Converting Image file to Base64
var imageBytes = pfImage.readAsBytesSync();
String base64Image = base64Encode(imageBytes);
print("base64 is =$base64Image");
putting into the map
var petData = Map<String, dynamic>();
petData['user_id'] = 55;
petData['name'] = "sdf";
petData['breed'] = "dsf";
petData['StrImageBase64'] =base64Image != null ? base64Image : "";
converting to json string
print("map>>" + json.encode(map));
Some More Info
I have checked it locally as well by putting base64string into map and then print it, the result is in reduced string.
petData['StrImageBase64'] ="/9j/4AAQSkZJRgABAQAAAQABAAD/4RllRXhpZgAASUkqAAgAAAAHABoBBQABAAAAYgAAABsBBQABAAAAagAAACgBAwABAAAAAgAAADIBAgAUAAAAcgAAABMCAwABAAAAAQAAAGmHBAABAAAAhgAAACWIBAABAAAA6AAAACoBAABIAAAAAQAAAEgAAAABAAAAMjAxOToxMToxMCAwNTo1NTozMwAHAACQBwAEAAAAMDIxMAGRBwAEAAAAAQIDAAqSBQABAAAA4AAAAACgBwAEAAAAMDEwMAGgAwABAAAA//8AAAKgBAABAAAAAAUAAAOgBAABAAAAwAMAAAAAAAAkEwAA6AMAAAIABwAFAAMAAAAGAQAAHQACAAsAAAAeAQAAAAAAAAAAAAABAAAANwAAAAEAAAAfAAAAAQAAADIwMTk6MTE6MTAAAAIAAQIEAAEAAABIAQAAAgIEAAEAAAAVGAAAAAAAAP/Y/+AAEEpGSUYAAQEAAAEAAQAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgA8AFAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX2";
print("json.encode =${json.encode(petData)}");
UPDATED
It is not possible, that the map can reduce the value, or Json.decode(map) returns the reduced base64 string, Actually its VS code editor issue for not showing full base64 value.

Encoding a String in NetSuite SuiteScript 2.0

I have to perform the following encoding on a string:
Calculate SHA1 hash value, with output in hexadecimal format
Apply a BASE64 encoding to the resulted hash
I'm trying to do this in the code below, 'str' being the input and 'digest' the final encoded string.
I've tried different ways without much success. The current code (below) throws an error:
WrappedException: Wrapped java.lang.IllegalArgumentException: contains illegal character for hexBinary: crypto.SecretKey
var str = nonce + timestamp + secret;
var secureString = HTTPS.createSecureString({
input: str
});
secureString = secureString.hash({
algorithm: CRYPTO.HashAlg.SHA1
});
var hexString = HTTPS.createSecretKey({
encoding: HTTPS.Encoding.HEX,
guid: secureString
});
var digest = ENCODE.convert({
string: hexString,
inputEncoding: ENCODE.Encoding.HEX,
outputEncoding: ENCODE.Encoding.BASE_64
});

Swift 4 hex string to binary string

Noted that the old method to convert a hex string to a binary string has been removed from swift i.e. : String(hex, radix: 2) -> binary string
What is an alternative in swift 4?
You need first to convert your hexaString to an Array of Bytes [UInt8]. Then you can use String(_, radix:) to convert the bytes to binary. Note that if you would like to return a String instead of an array of strings [String] you would need to add leading zeros to make your binary strings length consistent (8 characters):
extension String {
typealias Byte = UInt8
var hexaToBytes: [Byte] {
var start = startIndex
return stride(from: 0, to: count, by: 2).compactMap { _ in // use flatMap for older Swift versions
let end = index(after: start)
defer { start = index(after: end) }
return Byte(self[start...end], radix: 16)
}
}
var hexaToBinary: String {
return hexaToBytes.map {
let binary = String($0, radix: 2)
return repeatElement("0", count: 8-binary.count) + binary
}.joined()
}
}
let hexString = "00ff01fe"
hexString.hexaToBinary // "00000000111111110000000111111110"
I don't recall any function that would convert a hex string to another string of arbitrary radix. Perhaps you are thinking about the initializer functions that convert between strings and integer values (and vice versa) using an arbitrary radix:
let hex = "00ff01fe"
let value = UInt64(hex, radix: 16)!
let binary = String(value, radix: 2)
let paddedBinary = repeatElement("0", count: 64 - binary.count) + binary
But that only applies when the hex string represents a 64 bit value, but it illustrates the basic idea. Convert to some integer type, and then convert back to binary, padding it out with zeros.
If you have a hex string that is longer than that, you cannot use the above. But you can map the individual characters of your hex string to numeric values, build binary representation of each, zero pad them, and use joined to concatenate them together:
let hex = "ffeeddccbbaa99887766554433221100"
let result = hex.compactMap { c -> String? in
guard let value = Int(String(c), radix: 16) else { return nil }
let string = String(value, radix: 2)
return repeatElement("0", count: 4 - string.count) + string
}.joined()