Casting an int to Uint8 in Dart - flutter

I am using the ffi and tyed_data Dart libraries and keep running into an error with this line of code,
Uint8 START_OF_HEADER = 1 as Uint8;
My error:
type 'int' is not a subtype of type 'Uint8' in type cast
What am I doing wrong here? Another strange thing is that I can write this line of code using these libraries and my IDE will compile and not throw an error, that is until you use that line of code. I'm using Intellij version 2019.2.4

You are trying to create an instance of a Uint8 in Dart, but that's not possible - that type is just a marker.
/// [Uint8] is not constructible in the Dart code and serves purely as marker in
/// type signatures.
You'll just use those markers in the typedefs, for example to describe a C function taking two signed 32 bit ints and returning signed 32 bit int:
typedef native_sum_func = Int32 Function(Int32 a, Int32 b);
this will be paired with an equivalent Dart-like typedef
typedef NativeSum = int Function(int a, int b);
Dart ffi is responsible for converting a and b from Dart ints into 32 bit C ints and for converting the return value back to a Dart int.
Note that you can create a pointer to these C types, for example Pointer<Uint8> using the allocate method from package:ffi.

Related

Negative integer literal converted to generic unsigned integer type without warning

In this simple piece of code, I'm using the integer literal -1 in a context where a value of type T is expected. T conforms to FixedWidthInteger so it's unknown at compile time whether the literal can be converted to the actual type T. If T is set to an unsigned integer type, the -1 simply becomes a 0. I would have expected a runtime error, or at least a warning at compile time. Is this a bug or is this documented somewhere?
struct Bad<T: FixedWidthInteger> {
func getNegativeOne() -> T {
return -1
}
}
print(Bad<UInt32>().getNegativeOne())
When running it from the swift repl:
$ swift
Welcome to Swift version 5.5.2-dev.
Type :help for assistance.
1> [paste code]
0

Mypy fails to find a type error in simple one line function [duplicate]

Why does "mypy" consider "int" as a subtype of "float"? A subtype shall support all methods of its supertype, but "float" has methods, which "int" does not support:
test.py:
def f(x : float) -> bool:
return x.is_integer()
print(f(123.0))
print(f(123))
The static type checker accepts passing an "int" argument for a "float" parameter:
(3.8.1) myhost% mypy test.py
Success: no issues found in 1 source file
But this does not guarantee, that there are no errors at runtime:
(3.8.1) myhost% python test.py
True
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(f(123))
File "test.py", line 2, in f
return x.is_integer()
AttributeError: 'int' object has no attribute 'is_integer'
because "float" has additional methods, which "int" does not have.
'Why does "mypy" consider "int" as a subtype of "float"?'
Because practicality has so far been considered to beat purity here. This is not to say that one could not propose that typing define a Scalar type that would include ints and floats but only be valid for arithmetic operations.
Note that int / int was changed in 3.0 so that float(int / int) == float(int) / float(int), to make int and float arithmetic consistent for equal int and float values.
Note also that a type-check passing does not mean no runtime errors: division by zero and overflow are still possible, as well as many others.
As #juanpa.arrivillaga pointed out, the explanation is on https://mypy.readthedocs.io/en/latest/duck_type_compatibility.html.
A subtype shall support all methods of its supertype, but "float" has methods, which "int" does not support
int is not a subtype of float, so it doesn't have to support methods of float.
The mechanism is good because passing integer values shouldn't cause errors, unless you really want them as in your example. You explicitly tried to use a method which doesn't exist. In common situations, we only make arithmetic operations on numbers, so a problem rarely exists and you can always avoid it by adding .0 as you wrote.
It is a common behavior in most languages to assume that int is a special case of float, consider for example C++ int to float implicit conversion.

conversion of string to int and int to string using static_cast

I am just not able to convert different datatypes in c++,I know that c++ is a strong type language so,I
used here static_cast but I am facing a problem the error messages are
invalid static_cast from type 'std::string {aka std::basic_string}' to type 'int'
invalid conversion from 'int' to 'const char*' [-fpermissive]
#include <vector>
#include <iostream>
using namespace std;
int main()
{
string time;
string t2;
cin >> time;
int hrs;
for(int i=0;i!=':';i++)
{
t2[i]=time[i];
}
hrs=static_cast<int>(t2);
hrs=hrs+12;
t2=static_cast<string>(hrs);
for(int i=0;i!=':';i++)
{
time[i]=t2[i];
}
cout<<time;
return 0;
}
Making a string from an int (and the converse) is not a cast.
A cast is taking an object of one type and using it, unmodified, as if it were another type.
A string is a pointer to a complex structure including at least an array of characters.
An int is a CPU level structure that directly represents a numeric value.
An int can be expressed as a string for display purposes, but the representation requires significant computation. On a given platform, all ints use exactly the same amount of memory (64 bits for example). However, the string representations can vary significantly, and for any given int value there are several common string representations.
Zero, as an int on a 64 bit platform, consists of 64 bits at low voltage. As a string, it can be represented with a single byte "0" (high voltage on bits 4 and 5, low voltage on all other bits), the text "zero", the text "0x0000000000000000", or any of several other conventions that exist for various reasons. Then you get into the question of which character encoding scheme is being used - EBCDIC, ASCII, UTF-8, Simplified Chinese, UCS-2, etc.
Determining the int from a string requires a parser, and producing a string from an int requires a formatter.

Swift float multiplication error

This code fails:
let element: Float = self.getElement(row: 1, column: j)
let multiplier = powf(-1, j+2)*element
with this error:
Playground execution failed: :140:51: error: cannot invoke '*' with an argument list of type '(Float, Float)'
let multiplier = powf(-1, j+2)*element
Bear in mind that this occurs in this block:
for j in 0...self.columnCount {
where columnCount is a Float. Also, the first line does execute and so the getElement method indeed returns a Float.
I am completely puzzled by this as I see no reason why it shouldn't work.
There is no implicit numeric conversion in swift, so you have to do explicit conversion when dealing with different types and/or when the expected type is different than the result of the expression.
In your case, j is an Int whereas powf expects a Float, so it must be converted as follows:
let multiplier = powf(-1, Float(j)+2)*element
Note that the 2 literal, although usually considered an integer, is automatically inferred a Float type by the compiler, so in that case an explicit conversion is not required.
I ended up solving this by using Float(j) instead of j when calling powf(). Evidently, j cannot be implicitly converted to a Float.

IPhone SDK - How to detect variable type (float or double)?

How do I detect whether a variable is float, double, int, etc.?
Thanks.
Objective-C is not like PHP or other interpreted languages where the 'type' of a variable can change according to how you use it. All variables are set to a fixed type when they are declared and this cannot be changed. Since the type is defined at compile time, there is no need to query the type of a variable at run-time.
For example:
float var1; // var1 is a float and can't be any other type
int var2; // var2 is an int and can't be any other type
NSString* var3; // var3 is a pointer to a NSString object and can't be any other type
The type is specified before the variable name, also in functions:
- (void)initWithValue:(float)param1 andName:(NSString*)param2
{
// param1 is a float
// param2 is a pointer to a NSString object
}
So as you can see, the type is fixed when the variable is declared (also you will notice that all variables must be declared, i.e. you cannot just suddenly start using a new variable name unless you've declared it first).
In a compiled C based language (outside of debug mode with symbols), you can't actually "detect" any variable unless you know the type, or maybe guess a type and get lucky.
So normally, you know and declare the type before any variable reference.
Without type information, the best you can do might be to dereference a pointer to random unknown bits/bytes in memory, and hopefully not crash on an illegal memory reference.
Added comment:
If you know the type is a legal Objective C object, then you might be able to query the runtime for additional information about the class, etc. But not for ints, doubles, etc.
Use sizeof. For double it will be 8. It is 4 for float.
double x = 3.1415;
float y = 3.1415f;
printf("size of x is %d\n", sizeof(x));
printf("size of y is %d\n", sizeof(y));