Signed Hex to Signed Int Swift - ios

I've seen a lot of questions converting hex to int, but these are all of the unsigned-> unsigned variety. How could I convert signed hex to an Int?
eg.
somefunc('0xfffff830')
= -2000

Your question implies that you are dealing with 32-bit signed integers
(otherwise 0xfffff830 could not be considered as negative),
so this would work:
let num = "0xfffff830"
let x = Int32(truncatingBitPattern: strtoul(num, nil, 16))
println(x) // -2000
strtoul() converts the hex string to an unsigned integer UInt, and
Int32(truncatingBitPattern:) creates a (signed) 32-bit integer
from the lowest 32 bits of the given argument.
Updated for Swift 4:
let num = "0xfffff830"
let x = Int32(bitPattern: UInt32(num.dropFirst(2), radix: 16) ?? 0)
print(x) // -2000

You could use conversion to unsigned and then convert the unsigned to signed.
let num = "0xfffff830"
var result: UInt32 = 0
let converter = NSScanner(string: num)
converter.scanHexInt(&result)
print(unsafeBitCast(result, Int32.self)) // prints -2000

An approach
var hex = UInt32(0xfffff830)
let signedHex : Int
if hex > UInt32.max / 2 {
signedHex = -Int(~hex + 1) // ~ is the Bitwise NOT Operator
} else {
signedHex = Int(hex)
}

Related

Convert double to binary representation

I'm using bit shift operators on ints to convert to binary representation like that:
String toBinary(int i) {
var bytes = Uint8List(8);
bytes[0] = i >> 56;
bytes[1] = i >> 48;
bytes[2] = i >> 40;
bytes[3] = i >> 32;
bytes[4] = i >> 24;
bytes[5] = i >> 16;
bytes[6] = i >> 8;
bytes[7] = i;
return String.fromCharCodes(bytes);
}
Now I need to do the same thing for doubles, but double does not define bit shift operators. However, as doubles are also represented in 64 bit, is there a way to convert them to binary format?
First of all Dart already provides a ByteData class so in this case you can avoid using the bit shift operation and do instead:
var byteData = ByteData(8);
byteData.setUint64(0, 256);
var bytes = byteData.buffer.asUint8List();
which will produce the same byte list.
Given that you can use the setFloat64 method on ByteData to set a double and then get the binary representation.

Calculate high byte and low byte in swift iOS?

How to calculate the highByte and lowByte of any number;
Example :
let mValue = 26513
hex representation of mValue = 0x6791
Then how find high and low byte of above number?
Updated for swift :
below solution works for me:
let mVal = 26513 // hex value of mVal = 0x6791 (UInt16)
let highByte = (mVal >> 8) & 0xff // hex value of highByte = 0x0067 (UInt8)
let lowByte = mVal & 0xff // hex value of lowByte = 0x0091 (UInt8)
print("highByte: \(highByte)\nLowByte: \(lowByte)")

Binary operator '/' cannot be applied to two 'UInt32' operands

Here is my code.
var frameCount = INT_MAX
...
let totalSize: UInt32 = 4096
let itemSize: UInt32 = 64
frameCount = totalSize / itemSize
I get "Binary operator '/' cannot be applied to two 'UInt32' operands" error message.
Is it really impossible or what did I miss?
The error message is a bit misleading. INT_MAX is defined as
public var INT_MAX: Int32 { get }
so with
var frameCount = INT_MAX
frameCount is defined as a variable of type Int32.
The result of the division totalSize / itemSize is a UInt32
however, and Swift does not implicitly convert types.
You can fix that by changing the initial definition to
var frameCount = UINT32_MAX
or perhaps simpler, let the compiler infer the type:
let totalSize: UInt32 = 4096
let itemSize: UInt32 = 64
let frameCount = totalSize / itemSize
If you need the result as a signed integer then you have to
convert it explicitly, e.g.
let frameCount = Int32(totalSize / itemSize)

How to convert a double to an int in Dart?

The following produces the below error:
int calc_ranks(ranks)
{
double multiplier = .5;
return multiplier * ranks;
}
The return type double is not a int, as defined by the method calc_ranks. How do I round/cast to an int?
Round it using the round() method:
int calc_ranks(ranks) {
double multiplier = .5;
return (multiplier * ranks).round();
}
You can use any of the following.
double d = 20.5;
int i = d.toInt(); // i = 20
int i = d.round(); // i = 21
int i = d.ceil(); // i = 21
int i = d.floor(); // i = 20
You can simply use toInt() to convert a num to an int.
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).toInt();
}
Note that to do exactly the same thing you can use the Truncating division operator :
int calc_ranks(ranks) => ranks ~/ 2;
I see a lot of answers, but with less description. Hope my answer will add some value.
Lets initalize the variable, and see how it will change with different methods.
double x = 8.5;
toInt()
It truncates the decimal value.
int a = x.toInt();
print(a); // 8
truncate()
It also truncates the decimal value.
int b = x.truncate();
print(b); // 8
round()
It returns the closest integer. It uses half up rounding mode.
int c = x.round();
print(c); // 9
ceil()
It returns the closest integer greater than the value.
int c = x.ceil();
print(c); // 9
floor()
It returns the closest integer smaller than the value.
int c = x.floor();
print(c); // 8
I looked at the answers above and added some more answers to make it a little easier to understand.
double value = 10.5;
Using toInt()
void main(){
double value = 10.5;
var y = value.toInt();
print(y);
print(y.runtimeType);
}
Using round()
The round() method returns the closest integer to the double.
void main(){
double value = 9.6;
var b = value.round();
print(b);
print(b.runtimeType);
}
Using ceil()
The ceil() method returns the smallest integer that is equal or greater than the given double.
void main(){
double value = 9.5;
var d = value.ceil();
print(d);
print(d.runtimeType);
}
Using floor()
The floor() method returns the greatest integer not greater than the given double.
void main(){
double value = 10.9;
var j = value.floor();
print(j);
print(j.runtimeType);
}
Conclusion
We’ve gone through 4 different techniques to convert a double to an integer in Dart and Flutter. You can choose from the method that fits your use case to solve your problem. Flutter is awesome and provides a lot of amazing features.
To convert double to int just this:
division
double01 ~/ double02
PS: The operator x ~/ y is more efficient than (x / y).toInt().
Multiplication, addition and subtraction
(double01 * double02).toInt
(double01 + double02).toInt
(double01 - double02).toInt
Its easy,
(20.8).round()
For String,
double.tryParse(20.8).round()
from string to int ->
if you string in int format like '10'
then use ---->
int.parse(value)
but if string in double format like '10.6'
then use like this ---->
double.parse(value).toInt()
convert double to int
doubleValue.toInt()
Try this!
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).truncate();
}
class CurrencyUtils{
static int doubletoint(double doublee) {
double multiplier = .5;
return (multiplier * doublee).round();
}
}
----------------------
CustomText( CurrencyUtils.doubletoint(
double.parse(projPageListss[0].budget.toString())
).toString(),
fontSize: 20,
color: Colors.white,
font: Font.QuicksandSemiBold,
),
There's another alternative, you can first cast the double to 'num' datatype and then convert to int using toInt().
double multiplier = .5;
return ((multiplier * ranks) as num).toInt();
The num type is an inherited data type of the int and double types.
You can cast both int and double to num, then cast it again to whatever you want
(double -> use toDouble(), int -> use toInt())

Convert 4 byte into a signed integer

I'm trying to parse a binary file in the browser. I have 4 bytes that represent a 32-bit signed integer.
Is there a straight forward way of converting this to a dart int, or do I have to calculate the inverse of two's complement manually?
Thanks
Edit: Using this for manually converting:
int readSignedInt() {
int value = readUnsignedInt();
if ((value & 0x80000000) > 0) {
// This is a negative number. Invert the bits and add 1
value = (~value & 0xFFFFFFFF) + 1;
// Add a negative sign
value = -value;
}
return value;
}
You can use ByteArray from typed_data library.
import 'dart:typed_data';
int fromBytesToInt32(int b3, int b2, int b1, int b0) {
final int8List = new Int8List(4)
..[3] = b3
..[2] = b2
..[1] = b1
..[0] = b0;
return int8List.asByteArray().getInt32(0);
}
void main() {
assert(fromBytesToInt32(0x00, 0x00, 0x00, 0x00) == 0);
assert(fromBytesToInt32(0x00, 0x00, 0x00, 0x01) == 1);
assert(fromBytesToInt32(0xF0, 0x00, 0x00, 0x00) == -268435456);
}
Place the 4 bytes in a ByteArray and extract the Int32 like this:
import 'dart:scalarlist';
void main() {
Int8List list = new Int8List(4);
list[0] = b0;
list[1] = b1;
list[2] = b2;
list[3] = b3;
int number = list.asByteArray().getInt32(0);
}
John
I'm not exactly sure what you want, but maybe this code sample might get you ideas:
int bytesToInteger(List<int> bytes) {
var value = 0;
for (var i = 0, length = bytes.length; i < length; i++) {
value += bytes[i] * pow(256, i);
}
return value;
}
So let's say we have [50, 100, 150, 250] as our "4 bytes", the ending result is a 32-bit unsigned integer. I have a feeling this isn't exactly what you are looking for, but it might help you.

Resources