I am converting Java code to Dart, but I am stuck in Little Endian oder, Any ideas to help me?
Java:
void displayString(byte[] record) {
ByteBuffer bb = ByteBuffer.wrap(record);
bb.order(ByteOrder.LITTLE_ENDIAN);
.....
}
Dart:
_displayString(List<int> record) {
var _list = Uint8List.fromList(record);
// HOW TO ORDER LITTLE ENDIAN Like Java
.....
}
The closest equivalent to Java Byte buffer is Dart's ByteData.
var byteData = _list.buffer.asByteData();
You can't set its order globally, but you can specify it for each get or set.
byteData.setFloat32(0, 3.04, Endian.little);
Related
I am trying to read data back from a custom-built bluetooth board that simply sends back a string of data like this:
printf("Read 0x%2.2X%2.2X%2.2X%2.2X\n\r", d1, d2, d3, d4);
And the value I expect to get back is "Read 0xF2000080\n\r"
But what I get in the following flutter code is "RöØd 0xF2000080"
and sometimes different characters are the wrong ones in that string... the code that runs the printf sends back what is stored in memory for many different memory locations
uartTx.onValueChangedStream.listen((event1) {
processIncomingData(event1);
String stringVal = String.fromCharCodes(event1);
LLog.lLog(_tag, "build: uartTx event 1: String value ${stringVal}");
String stringVal2 = "";
event1.forEach((element) {
stringVal2 += element.toRadixString(16);
});
LLog.lLog(_tag, "build: uartTx event 1: String 2 value ${stringVal2}");
String hexVal = hex.encode(event1);
LLog.lLog(_tag, "build: uartTx event 1: Hex value ${hexVal}");
});
void processIncomingData(List<int> newBytes) {
// convert the List<int> to a list of <byte> sized objects
Uint8List convBytes = Uint8List.fromList(newBytes);
// convert the List<int> into a string:
String stringVal = String.fromCharCodes(newBytes);
// which looks a lot like this:
// [9X0CAF01460E4103][AP0200][BL0200][CL0210][DV0A312E302E30]
// [ and ] apparently are delimiters/terminations between commands
LLog.lLog(_tag, 'processIncomingData: Uint8List of bytes received are = $convBytes and the string conversion of that is $stringVal');
I tried to listen for incoming data on a bluetooth connection:
uartTx.onValueChangedStream.listen((event1) {
processIncomingData(event1);
I get bad characters in the List received:
processIncomingData(event1);
void processIncomingData(List<int> newBytes) {
// convert the List<int> to a list of <byte> sized objects
Uint8List convBytes = Uint8List.fromList(newBytes);
which looks like this:
"RöØd 0xF2000080"
I expect just a regular set of ascii characters instead:
"Read 0xF2000080\n\r"
Lets Say this is My Text. Now I want to Extract All 4 Variable Separately from the text
"ScanCode=? scanMsg= ? ItemName=? ID= ?\n"
Please Help i need this is Dart, Flutter
The solution I developed first splits the data according to the space character. It then uses the GetValue() method to sequentially read the data from each piece. The next step will be to use the data by transforming it accordingly.
This example prints the following output to the console:
[ScanCode=1234, ScanMessage=Test, Itemname=First, ID=1]
[1234, Test, First, 1]
The solution I developed is available below:
void main()
{
String text = "ScanCode=1234 ScanMessage=Test ItemName=First ID=1";
List<String> original = text.split(' ');
List<String> result = [];
GetValue(original, result);
print(original);
print(result);
}
void GetValue(List<String> original, List<String> result)
{
for(int i = 0 ; i < original.length ; ++i)
{
result.insert(i, original[i].split('=')[1]);
}
}
I am studying at night graduate school.
While studying the cryptographic hash function, I found information that the speed of the SHA3 hash function is faster than the speed of the SHA2 hash function.
So, using JMH benchmarking in actual JAVA, I tried to compare the performance of SHA512/256 of SHA2 and SHAKE256 of SHA3 series, but there doesn't seem to be much difference than I thought.
The library I used and the source code I wrote are as follows.
SHA512-256
import java.security.MessageDigest;
public static byte[] digest(byte[] data) throws NoSuchAlgorithmException
{
CryptoProvider.setupIfNeeded();
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA512/256");
digest.update(Arrays.copyOf(data, data.length));
return digest.digest();
}
SHAKE256 (use 2 methods)
import org.bouncycastle.crypto.digests.SHAKEDigest;
public static byte[] shakeDigest(byte[] data, int returnLength) throws NoSuchAlgorithmException
{
CryptoProvider.setupIfNeeded();
SHAKEDigest digest = new SHAKEDigest(256);
byte[] hashBytes = new byte[returnLength];
digest.update(data, 0, data.length);
digest.doFinal(hashBytes, 0);
digest.reset();
return Arrays.copyOf(hashBytes, returnLength);
}
import com.github.aelstad.keccakj.fips202.Shake256;
public static byte[] shakeDigest2(byte[] data, int returnLength) throws Exception
{
CryptoProvider.setupIfNeeded();
Shake256 digest = new Shake256();
digest.getAbsorbStream().write(data);
byte[] hashBytes = new byte[returnLength];
digest.getSqueezeStream().read(hashBytes);
digest.reset();
return Arrays.copyOf(hashBytes, returnLength);
}
I'm wondering if I'm missing something, or if there exists a SHAKE256 library that's closer to perfection than the one I used.
Please help.
Thank you.
There is a method in bitconverter class in java which has a method called toInt16
But in dart i am unable to cast short as Int16
public static short toInt16( byte[] bytes, int index )
throws Exception {
if ( bytes.length != 8 )
throw new Exception( "The length of the byte array must be at least 8 bytes long." );
return (short) ( ( 0xff & bytes[index] ) << 8 | ( 0xff & bytes[index + 1] ) << 0 );
}
can someone help me with this conversion to dart language ?
Here is the updated dart version of answer that i followed using the ByteData class suggested by emerssso and this works for me
int toInt16(Uint8List byteArray, int index)
{
ByteBuffer buffer = byteArray.buffer;
ByteData data = new ByteData.view(buffer);
int short = data.getInt16(index, Endian.little);
return short;
}
I had to specifically set Endian.little because originally getInt16 method is set to BigEndian but my byte data was in former order
I think you are looking for one of the methods on the ByteData class available in dart:typed_data. Wrap your byte array in a ByteData via ByteData.view() and then you can arbitrarily access bytes as a specified type. You could then do i.e. byteData.getInt16(index);.
https://api.dart.dev/stable/2.7.1/dart-typed_data/ByteData-class.html
While GWT is not emulate all java's core, what can be used as alternative for:
String.format("The answer is - %d", 42)?
What is the ellegant and efficient pattern to inject arguments to message in GWT?
One elegant solution is using SafeHtml templates. You can define multiple such templates in an interface like:
public interface MyTemplates extends SafeHtmlTemplates {
#Template("The answer is - {0}")
SafeHtml answer(int value);
#Template("...")
...
}
And then use them:
public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class);
...
Label label = new Label(TEMPLATES.answer(42));
While this is a little bit more work to set up, it has the enormous advantage that arguments are automatically HTML-escaped. For more info, see https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml
If you want to go one step further, and internationalize your messages, then see also https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages
You can simply write your own format function instead of doing brain storm.
public static String format(final String format, final String... args,String delimiter) {
String[] split = format.split(delimiter);//in your case "%d" as delimeter
final StringBuffer buffer= new StringBuffer();
for (int i= 0; i< split.length - 1; i+= 1) {
buffer.append(split[i]);
buffer.append(args[i]);
}
buffer.append(split[split.length - 1]);
return buffer.toString();
}
Because most (as in 99.999%) message formats are static, known at compile-time, the way GWT approaches it is to parse them at compile-time.
You'll generally use a Messages subinterface for its ability to localize the message, but you'll sometimes rather need SafeHtmlTemplates.
In the 0.001% when template is not known at compile time you can use Javascript sprintf (see: http://www.diveintojavascript.com/projects/javascript-sprintf) as in:
public static native String format (String format, JsArrayMixed values) /*-{
return vsprintf(format, values);
}-*/;
You can write your own.
I wrote a version that just work with Strings(%s):
public static String format(final String format, final Object... args)
{
checkNotNull(format);
checkNotNull(args);
final String pattern = "%s";
int start = 0, last = 0, argsIndex = 0;
final StringBuilder result = new StringBuilder();
while ((start = format.indexOf(pattern, last)) != -1)
{
if (args.length <= argsIndex)
{
throw new IllegalArgumentException("There is more replace patterns than arguments!");
}
result.append(format.substring(last, start));
result.append(args[argsIndex++]);
last = start + pattern.length();
}
if (args.length > argsIndex)
{
throw new IllegalArgumentException("There is more arguments than replace patterns!");
}
result.append(format.substring(last));
return result.toString();
}
why not writing a method like:
String appendAnswer(int result) {
return "The answer is - " + Integer.toString(result);
}
is resolving your problem because you do nothing like formatting in your code.
if you ever face the problem like converting integer/byte to Hex String you should use:
Integer.toString(int, 16);
I don't know GWT much but I am working on a GWT project and I needed this. While trying some alternatives, I have found that this is working;
import java.text.MessageFormat;
MessageFormat.format("The answer is - {0}", 42);
I don't know if the project's developers added something special to make this work or it is working by default.