Convert int to string with leading zeros - f#

I have an integer which I want to convert to a string with leading zeros.
So I have 1 and want to turn it into 01. 14 should turn into 14 not 014.
I tried:
let str = (string 1).PadLeft(2, '0') // visual studio suggested this one
let str = (string 1).PadLeft 2 '0'
let str = String.PadLeft 2 '0' (string 1)
But neither work :(
When I search for something like this with F# I get stuff with printfn but I don't want to print to stdout :/
Disclaimer: This is my first F#

You can use sprintf which returns a string rather than printing to stdout. Any of the print functions that start with an s return a string.
Use %0i to pad with zeroes. Add the length of the intended string between 0 and i. For example, to pad to four zeroes, you can use:
sprintf "%04i" 42
// returns "0042"

Related

Systemverilog string variable as format specifier for $display/$write

I'm trying to create a variable format specifier for use in $display/$write. I've tried a large number of things, but here is what I have at the moment.
What I want to end up with is: $display(format_var,data_1,data_2), where the format string is pre-calculated using $sformatf or other.
Code:
module test;
function void pprint(input int data_1,input int field_1,input int data_2,input int field_2);
string format;
begin
format = $sformatf("%0d'h%%%0dx,%0d'h%%%0dx",field_1,field_1/4,field_2,field_2/4);
$display("format = %s",format);
$display(format,data_1,data_2);
end
endfunction
initial
begin
pprint(5,8,73737229,128);
$stop;
end
endmodule
The output I expect is:
format = 8'h%2x,128'h%32x
8'h05,128'h000000000000000000000000465240D
The output I get is:
format = 8'h%2x,128'h%32x
8'h%2x,128'h%32x 5 73737229
What do I need to do? The simulator is Vivado 2020.3
Later:
Trying more things, the following function does do what I want. My conclusion is that $display/$write can't take a variable as the format string, but $sformatf can.
function void pprint(input int data_1,input int field_1,input int data_2,input int field_2);
string format;
string outstr;
begin
format = $sformatf("%0d'h%%%0dx,%0d'h%%%0dx",field_1,field_1/4,field_2,field_2/4);
$display("format = %s",format);
$display("%s",$sformatf(format,data_1,data_2));
end
endfunction
Try:
function void pprint(
input logic [4095:0] data_1,
input int field_1,
input logic [4095:0] data_2,
input int field_2 );
string format;
format = $sformatf("%0d'h%%%0dh,%0d'h%%%0dh",
field_1, (field_1+3)/4,
field_2, (field_2+3)/4 );
$display("format = %s",format);
$display($sformatf(format,data_1,data_2));
endfunction
This should give you the output:
format = 8'h%02h,128'h%032h
8'h05,128'h000000000000000000000000465240D
Adding a zero between the % and digit could tells the simulator to pad the upper bits with zeros.
For some reason $display(format,data_1,data_2) did not use the format on simulators on edaplayground, but it did work with $sformatf so I simply nested it.
I needed to increase the bit width of the input data otherwise it would show leading zeros over 8 digits. Adjust if necessary.
Adding 3 to the field is for handling non multiples of 4. It will always round down after division.
According to section 21.3.3 Formatting data to a string of the SystemVerilog LRM, only $sformat and $sformatf have a specific formatting argument that can be a string literal or string variable. All other output tasks like $display treat any string literal argument as format specifiers and do not interpret the strings inside string variables for formatting.

How to get the last n-characters in a string in Dart?

How do I get the last n-characters in a string?
I've tried using:
var string = 'Dart is fun';
var newString = string.substring(-5);
But that does not seem to be correct
var newString = string.substring(string.length - 5);
Create an extension:
extension E on String {
String lastChars(int n) => substring(length - n);
}
Usage:
var source = 'Hello World';
var output = source.lastChars(5); // 'World'
While #Alexandre Ardhuin is correct, it is important to note that if the string has fewer than n characters, an exception will be raised:
Uncaught Error: RangeError: Value not in range: -5
It would behoove you to check the length before running it that way
String newString(String oldString, int n) {
if (oldString.length >= n) {
return oldString.substring(oldString.length - n)
} else {
// return whatever you want
}
}
While you're at it, you might also consider ensuring that the given string is not null.
oldString ??= '';
If you like one-liners, another options would be:
String newString = oldString.padLeft(n).substring(max(oldString.length - n, 0)).trim()
If you expect it to always return a string with length of n, you could pad it with whatever default value you want (.padLeft(n, '0')), or just leave off the trim().
At least, as of Dart SDK 2.8.1, that is the case. I know they are working on improving null safety and this might change in the future.
var newString = string.substring((string.length - 5).clamp(0, string.length));
note: I am using clamp in order to avoid Value Range Error. By that you are also immune to negative n-characters if that is somehow calculated.
In fact I wonder that dart does not have such clamp implemented within the substring method.
If you want to be null aware, just use:
var newString = string?.substring((string.length - 5).clamp(0, string.length));
I wrote my own solution to get any no of last n digits from a string of unknown length, for example the 5th to the last digit from an n digit string,
String bin='408 408 408 408 408 1888';// this is the your string
// this function is to remove space from the string and then reverse the
string, then convert it to a list
List reversed=bin.replaceAll(" ","").split('').reversed.toList();
//and then get the 0 to 4th digit meaning if you want to get say 6th to last digit, just pass 0,6 here and so on. This second reverse function, return the string to its initial arrangement
var list = reversed.sublist(0,4).reversed.toList();
var concatenate = StringBuffer();
// this function is to convert the list back to string
list.forEach((item){
concatenate.write(item);
});
print(concatenate);// concatenate is the string you need

Dart: convert decimal to hex

I've been searching for a way to convert decimal numbers to hexadecimal format in the Dart programming language.
The hex.encode method in the HexCodec class, for example, cannot convert the decimal 1111 (which has a hex value of 457) and instead gives an exception:
FormatException: Invalid byte 0x457. (at offset 0)
How do I convert a decimal number to hex?
int.toRadixString(16)
does that.
See also https://groups.google.com/a/dartlang.org/forum/m/#!topic/misc/ljkYEzveYWk
Here is a little fuller example:
final myInteger = 2020;
final hexString = myInteger.toRadixString(16); // 7e4
The radix just means the base, so 16 means base-16. You can use the same method to make a binary string:
final binaryString = myInteger.toRadixString(2); // 11111100100
If you want the hex string to always be four characters long then you can pad the left side with zeros:
final paddedString = hexString.padLeft(4, '0'); // 07e4
And if you prefer it in uppercase hex:
final uppercaseString = paddedString.toUpperCase(); // 07E4
Here are a couple other interesting things:
print(0x7e4); // 2020
int myInt = int.parse('07e4', radix: 16);
print(myInt); // 2020

How do I compare two characters in Dart?

I want to compare two characters. Something like this:
if ('a' > 'b')
However, the above code is comparing two strings.
How do I do this in Dart?
Dart doesn't have a 'char' or 'character' type. You can get the UTF-16 character code from any point in a string, and compare that.
Use codeUnitAt to get the actual character code from a string.
if ('a'.codeUnitAt(0) > 'b'.codeUnitAt(0))
See the codeUnitAt docs: https://api.dartlang.org/docs/channels/stable/latest/dart_core/String.html#codeUnitAt
String in Dart implements the Comparable interface. You can use compareTo to compare them.
String a = 'a';
String b = 'b';
String c = 'a';
print('value: ${a.compareTo(b)}'); // prints "value: -1"
print('value: ${a.compareTo(c)}'); // prints "value: 0"
print('value: ${b.compareTo(a)}'); // prints "value: 1"

F# GetDigitValue value or construct not valid

I am new to F# and would like to have an advice.
I would like to use the GetDigitValue function.
open System
open System.Drawing
open System.Globalization
let getSubscript ichar =
match ichar with
|1 -> GetDigitValue(843)
| _ -> GetDigitVale(852)
I have the following error: The value or constructor 'getDigitValue" is not defined.
Without further information I can't really tell what you are trying to do.
GetDigitValue is a static method of the CharUnicodeInfo class.
It is used like this:
let testString = "1234567890"
let digitValue = CharUnicodeInfo.GetDigitValue(testString, 3)
This returns the digit value for the 3rd character in the string. It also works with a single character too.
let test = '5'
let digitvalue = CharUnicodeInfo.GetDigitValue(test)
Update:
To get the superscript of a string I think the Numeric value will return this:
let superscriptTwo ="U+00B2"
let numericvalue = CharUnicodeInfo.GetNumericValue(superscriptTwo)
I would like to get the superscript of numbers.
Then I think you want this function that gives a unicode character that is the superscript of the given digit:
let superscriptOf n =
if 0<=n && n<10 then "⁰¹²³⁴⁵⁶⁷⁸⁹".[n] else
invalidArg "n" "Not a single digit number"
Note that F# supports unicode in F# code. You can even use unicode variable names like λ in F# code!

Resources