Why does a double of 65555 converted to byte produce a result of 19 in Kotlin?
That's because of a numerical conversion from a wider type to a type of a smaller size. The Double (IEEE 754 double precision number) has its integral part factored to the powers of two as 65555 = 217 + 24 + 22 + 20 = 65536 + 16 + 2 + 1, which is stored in binary form as (higher bits to lower):
... 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1
When this number is converted to Byte, only its lowest 8 bits are retained:
... _ _ _ _ _ _ _ _ _ _ 0 0 0 1 0 0 1 1
And that results into 24 + 22 + 20 = 16 + 2 + 1 = 19.
Because when you convert 65555 (or 65555.0) to a binary representation it takes more than one byte. So calling .toByte() takes the lowest one, which is 19.
65555 -> Binary == 1 00000000 00010011
^ ^^^^^^^^ ^^^^^^^^
1 0 19
Double 65555.0 gets converted to integer 65555 which is 0x10013. Conversion to Byte takes lower byte which is 0x13 (19 decimal).
Related
I want to know the function of operator &. For example:
SELECT (8 & 16)
In the last code if I change the second value (16) to another one, like 10, the result changes.
I read about it, but I didn't found an accurate answer.
Thank's for your help.
For SQL Server you can find the answer here https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15
The & bitwise operator performs a bitwise logical AND between the two expressions, taking each corresponding bit for both expressions. The bits in the result are set to 1 if and only if both bits (for the current bit being resolved) in the input expressions have a value of 1; otherwise, the bit in the result is set to 0.
If the left and right expressions have different integer data types (for example, the left expression is smallint and the right expression is int), the argument of the smaller data type is converted to the larger data type. In this case, the smallintexpression is converted to an int.
To come back to your Example:
If you compare 2 Integer numbers bitwise this will be calculated:
8 = 0 0 0 0 1 0 0 0
16 = 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 = 0
8 = 0 0 0 0 1 0 0 0
10 = 0 0 0 0 1 0 1 0
0 0 0 0 1 0 0 0 = 8
Hope that helps.
In MS SQL Server it is a bitwise AND operator.
If bits at any location are both 1, the result is 1.
1010 1010 = 170
0100 1011 = 75
0000 1010 = 10
Select 170 & 75
Returns 10
In most databases, & is the bitwise AND operator. What it does is translate its integer argument to their bit representation, and apply the AND operator to each individual bit (this is equivalent to multiplying each bit invidually):
For your operation 8 & 16:
8 is represented as 1000 in binary
16 corresponds to 10000
Performing the bitwise and:
01000
AND 10000
-----
00000 (0)
I need to split a string of 20 digits individually and multiply each single one by a value.
String (this string is in a text box) example: 11604999123400002586
After the split, I must do the following operation:
51 x 1º digit +
73 x 2º digit +
17 x 3º digit +
89 x 4º digit +
38 x 5º digit +
62 x 6º digit +
45 x 7º digit +
53 x 8º digit +
15 x 9º digit +
50 x 10º digit +
5 x 11º digit +
49 x 12º digit +
34 x 13º digit +
81 x 14º digit +
76 x 15º digit +
27 x 16º digit +
90 x 17º digit +
9 x 18º digit +
30 x 19º digit +
3 x 20º digit
In this example:
Result = 51x1 + 73x1 + 17x6 + 89x0 + 38x4 + 62x9 +
45x9 + 53x9 + 15x1 + 50x2 + 5x3 + 49x4 + 34x0 + 81x0 + 76x0 + 27x0 + 90x2
+ 9x5 + 30x8 + 3x6 = 2627
What would be the best way to do it?
In VBA you can do something like this:
Dim a(20) as Integer
a(1) = 51
a(2) = 73
…
a(20) = 3
Dim Result AS Long: Result = 0
For i = 1 to 20
Result = Result + CInt(Mid(MyString,i,1)) * a(i)
Next i
You can do it with SQL.
Create a table, say with name weights, with 2 columns:
id: Number
weight: Number
and insert these rows:
id weight
1 51
2 73
3 17
4 89
5 38
6 62
7 45
8 53
9 15
10 50
11 5
12 49
13 34
14 81
15 76
16 27
17 90
18 9
19 30
20 3
Then execute this query:
SELECT SUM(w.weight * val(mid('11604999123400002586', w.id, 1))) AS result
FROM weights AS w
Result:
2627
Consistency of structure is critical in string manipulation. Assume there will always be 20 digits in string and every record will have value.
Calculate 20 columns and add them together for the Total - here are 2:
SELECT Quotes.*, Mid([Data],1,1)*53 AS A, Mid([Data],2,1)*71 AS B, [A]+[B] AS Total FROM Quotes;
Could pull weight factor from table. DLookup is one way but domain aggregate can cause slow performance in large dataset so if weight factors will never change, probably don't want this:
SELECT Quotes.Data, Mid([Data],1,1)* DLookup("Weight","Factors","ID=1") AS A, Mid([Data],2,1)* DLookup("Weight","Factors","ID=2") AS B, [A]+[B] AS Total FROM Quotes;
A Cartesian relationship with aggregate calcs query using data and weight factors tables can calculate Total - Cartesian can also perform slowly with large dataset:
SELECT Quotes.ID, Sum(Mid([Data],[Factors].[ID],1)*[Weight]) AS Total
FROM Factors, Quotes
GROUP BY Quotes.ID;
A custom VBA function could return just the total. Call this function from query or textbox. The weight factors can be pulled from table or hard coded in an array construct.
Function GetTotal(strD) As Long
Dim rs As DAO.Recordset, x As Integer
Set rs = CurrentDb.OpenRecordset("SELECT Weight FROM Factors ORDER BY ID")
For x = 1 To 20
GetTotal = GetTotal + Mid(strD, x, 1) * rs!Weight
rs.MoveNext
Next
End Function
Is somebody able to explain what the below query is actually doing?
SELECT (Convert(int, 33558529) & 4096),((Convert(int, 33558529) & 1048576))
FROM dbo.example
Why does the first part return 4096 and the second part returns 0?
& performs a bitwise logical AND operation between two integer values. See the doc.
Here are the integer values converted to binary :
33558529 = 10000000000001000000000001
4096 = 1000000000000 1 bit match hence 1000000000000 or 4096
1048576 = 100000000000000000000 0 bit match hence 0
The & sign in T-SQL is the bitwise AND. It is used for bitwise comparison on numbers.
Why does the first part return 4096 and the second part returns 0?
Because the big number (33558529) includes the 4096 bit, but does not contain the 1048576 bit.
I find it easier to understand when you use smaller numbers, and write it out in binary. Suppose the big number you're checking is actually 9, written as binary 9 is
8 4 2 1
=======
1 0 0 1 <-- 9
If we were to perform bitwise AND logic on the above with the number 8 we would get
8 4 2 1
=======
1 0 0 1 <-- 9
1 0 0 0 <-- 8
-------
1 0 0 0 < -- result of ANDing 9 & 8 = 8
If we did the same exercise but with 2
8 4 2 1
=======
1 0 0 1 <-- 9
0 0 1 0 <-- 2
-------
0 0 0 0 <-- result of ANDing 9 & 2 = 0
& is the bitwise logical and operator - It performs the operation on
2 integer values.
Please refer :
Ampersand (&) operator in a SQL Server WHERE Clause
SELECT
(Convert(int, 33558529) & 4096),((Convert(int, 33558529) & 1048576))
FROM dbo.example
Its compare the bitwise data and gives the result
Check this link and compare the bit value
33558529 - 00000010 00000000 00010000 00000001
4096 - 00000000 00000000 00010000 00000000 means 1
1048576 - 00000000 00000000 00000000 00000000
Same you check the logic behind.
I want to write for example number 10 all the possible ways as a sum of units 3, 4, ..., n-1 (not 2)
for example i can write 10 as
10=10(units)
10=7 + 1*3 or
10=4 + 2*3 or
10=3 + 1*3 + 1*4 or
10=2 + 2*4 or ....
I dont care about the number of combinations!
I want the combinations!!! I mean an algoithm to output like this
un 3 4 5 6 7 8 9 10
-------------------
10 0 0 0 0 0 0 0 0
07 1 0 0 0 0 0 0 0
04 2 0 0 0 0 0 0 0
03 1 1 0 0 0 0 0 0
02 0 2 0 0 0 0 0 0 etc
any response is welcomed!!!
start with zero
try to add the largest possible number
store the result, if you arrive at the target sum
else if you ended with less than the target sum, go to (2)
else (if you ended with more than the target sum)
undo the last adding step, try to add one less instead. If you don't have any more smaller numbers to try, undo one more addition in past
if you run out of all possible additions, you already found all combinations and can exit.
Example:
target = 10
0
0 + 9 -> not there yet
0 + 9 + 9 -> too much, try something less
0 + 9 + 8 -> too much, try less
...
...
...
0 + 9 + 3 -> too much, cant try any less
0 + 8 -> not there yet
0 + 8 + 8 -> too much
...
...
...
0 + 8 + 3 -> too much, cant try any less
0 + 7 -> not there yet
0 + 7 + 7 -> too much
0 + 7 + 6 -> too much
...
...
...
0 + 7 + 3 -> thats it! save!
0 + 6 -> not yet
0 + 6 + 6 -> too much...
I hope you get the idea... :)
It will be much much faster, than trying all the possible combinations and selecting only the ones that sum to 10. This approach is called backtracking (https://en.wikipedia.org/wiki/Backtracking), because you try to go in some direction (adding the largest number), but when you fail (sum is too big), you track your progress back and then try something different.
You can then speed it up by trying the possibilities in more clever way (0 + 7 + 7 is too much by 4, so don't even try 0 + 7 + 6, but skip straight to 0 + 7 + 3).
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Write code to determine if a number is divisible by 3. The input to the function is a single bit, 0 or 1, and the output should be 1 if the number received so far is the binary representation of a number divisible by 3, otherwise zero.
Examples:
input "0": (0) output 1
inputs "1,0,0": (4) output 0
inputs "1,1,0,0": (6) output 1
This is based on an interview question. I ask for a drawing of logic gates but since this is stackoverflow I'll accept any coding language. Bonus points for a hardware implementation (verilog etc).
Part a (easy): First input is the MSB.
Part b (a little harder): First input is the LSB.
Part c (difficult): Which one is faster and smaller, (a) or (b)? (Not theoretically in the Big-O sense, but practically faster/smaller.) Now take the slower/bigger one and make it as fast/small as the faster/smaller one.
There's a fairly well-known trick for determining whether a number is a multiple of 11, by alternately adding and subtracting its decimal digits. If the number you get at the end is a multiple of 11, then the number you started out with is also a multiple of 11:
47278 4 - 7 + 2 - 7 + 8 = 0, multiple of 11 (47278 = 11 * 4298)
52214 5 - 2 + 2 - 1 + 4 = 8, not multiple of 11 (52214 = 11 * 4746 + 8)
We can apply the same trick to binary numbers. A binary number is a multiple of 3 if and only if the alternating sum of its bits is also a multiple of 3:
4 = 100 1 - 0 + 0 = 1, not multiple of 3
6 = 110 1 - 1 + 0 = 0, multiple of 3
78 = 1001110 1 - 0 + 0 - 1 + 1 - 1 + 0 = 0, multiple of 3
109 = 1101101 1 - 1 + 0 - 1 + 1 - 0 + 1 = 1, not multiple of 3
It makes no difference whether you start with the MSB or the LSB, so the following Python function works equally well in both cases. It takes an iterator that returns the bits one at a time. multiplier alternates between 1 and 2 instead of 1 and -1 to avoid taking the modulo of a negative number.
def divisibleBy3(iterator):
multiplier = 1
accumulator = 0
for bit in iterator:
accumulator = (accumulator + bit * multiplier) % 3
multiplier = 3 - multiplier
return accumulator == 0
Here... something new... how to check if a binary number of any length (even thousands of digits) is divisible by 3.
-->((0))<---1--->()<---0--->(1) ASCII representation of graph
From the picture.
You start in the double circle.
When you get a one or a zero, if the digit is inside the circle, then you stay in that circle. However if the digit is on a line, then you travel across the line.
Repeat step two until all digits are comsumed.
If you finally end up in the double circle then the binary number is divisible by 3.
You can also use this for generating numbers divisible by 3. And I wouldn't image it would be hard to convert this into a circuit.
1 example using the graph...
11000000000001011111111111101 is divisible by 3 (ends up in the double circle again)
Try it for yourself.
You can also do similar tricks for performing MOD 10, for when converting binary numbers into base 10 numbers. (10 circles, each doubled circled and represent the values 0 to 9 resulting from the modulo)
EDIT: This is for digits running left to right, it's not hard to modify the finite state machine to accept the reverse language though.
NOTE: In the ASCII representation of the graph () denotes a single circle and (()) denotes a double circle. In finite state machines these are called states, and the double circle is the accept state (the state that means its eventually divisible by 3)
Heh
State table for LSB:
S I S' O
0 0 0 1
0 1 1 0
1 0 2 0
1 1 0 1
2 0 1 0
2 1 2 0
Explanation: 0 is divisible by three. 0 << 1 + 0 = 0. Repeat using S = (S << 1 + I) % 3 and O = 1 if S == 0.
State table for MSB:
S I S' O
0 0 0 1
0 1 2 0
1 0 1 0
1 1 0 1
2 0 2 0
2 1 1 0
Explanation: 0 is divisible by three. 0 >> 1 + 0 = 0. Repeat using S = (S >> 1 + I) % 3 and O = 1 if S == 0.
S' is different from above, but O works the same, since S' is 0 for the same cases (00 and 11). Since O is the same in both cases, O_LSB = O_MSB, so to make MSB as short as LSB, or vice-versa, just use the shortest of both.
Here is an simple way to do it by hand.
Since 1 = 22 mod 3, we get 1 = 22n mod 3 for every positive integer.
Furthermore 2 = 22n+1 mod 3. Hence one can determine if an integer is divisible by 3 by counting the 1 bits at odd bit positions, multiply this number by 2, add the number of 1-bits at even bit posistions add them to the result and check if the result is divisible by 3.
Example: 5710=1110012.
There are 2 bits at odd positions, and 2 bits at even positions. 2*2 + 2 = 6 is divisible by 3. Hence 57 is divisible by 3.
Here is also a thought towards solving question c). If one inverts the bit order of a binary integer then all the bits remain at even/odd positions or all bits change. Hence inverting the order of the bits of an integer n results is an integer that is divisible by 3 if and only if n is divisible by 3. Hence any solution for question a) works without changes for question b) and vice versa. Hmm, maybe this could help to figure out which approach is faster...
You need to do all calculations using arithmetic modulo 3. This is the way
MSB:
number=0
while(!eof)
n=input()
number=(number *2 + n) mod 3
if(number == 0)
print divisible
LSB:
number = 0;
multiplier = 1;
while(!eof)
n=input()
number = (number + multiplier * n) mod 3
multiplier = (multiplier * 2) mod 3
if(number == 0)
print divisible
This is general idea...
Now, your part is to understand why this is correct.
And yes, do homework yourself ;)
The idea is that the number can grow arbitrarily long, which means you can't use mod 3 here, since your number will grow beyond the capacity of your integer class.
The idea is to notice what happens to the number. If you're adding bits to the right, what you're actually doing is shifting left one bit and adding the new bit.
Shift-left is the same as multiplying by 2, and adding the new bit is either adding 0 or 1. Assuming we started from 0, we can do this recursively based on the modulo-3 of the last number.
last | input || next | example
------------------------------------
0 | 0 || 0 | 0 * 2 + 0 = 0
0 | 1 || 1 | 0 * 2 + 1 = 1
1 | 0 || 2 | 1 * 2 + 0 = 2
1 | 1 || 0 | 1 * 2 + 1 = 0 (= 3 mod 3)
2 | 0 || 1 | 2 * 2 + 0 = 1 (= 4 mod 3)
2 | 1 || 2 | 2 * 2 + 1 = 2 (= 5 mod 3)
Now let's see what happens when you add a bit to the left. First, notice that:
22n mod 3 = 1
and
22n+1 mod 3 = 2
So now we have to either add 1 or 2 to the mod based on if the current iteration is odd or even.
last | n is even? | input || next | example
-------------------------------------------
d/c | don't care | 0 || last | last + 0*2^n = last
0 | yes | 1 || 0 | 0 + 1*2^n = 1 (= 2^n mod 3)
0 | no | 1 || 0 | 0 + 1*2^n = 2 (= 2^n mod 3)
1 | yes | 1 || 0 | 1 + 1*2^n = 2
1 | no | 1 || 0 | 1 + 1*2^n = 0 (= 3 mod 3)
1 | yes | 1 || 0 | 2 + 1*2^n = 0
1 | no | 1 || 0 | 2 + 1*2^n = 1
input "0": (0) output 1
inputs "1,0,0": (4) output 0
inputs "1,1,0,0": (6) output 1
shouldn't this last input be 12, or am i misunderstanding the question?
Actually the LSB method would actually make this easier. In C:
MSB method:
/*
Returns 1 if divisble by 3, otherwise 0
Note: It is assumed 'input' format is valid
*/
int is_divisible_by_3_msb(char *input) {
unsigned value = 0;
char *p = input;
if (*p == '1') {
value &= 1;
}
p++;
while (*p) {
if (*p != ',') {
value <<= 1;
if (*p == '1') {
ret &= 1;
}
}
p++;
}
return (value % 3 == 0) ? 1 : 0;
}
LSB method:
/*
Returns 1 if divisble by 3, otherwise 0
Note: It is assumed 'input' format is valid
*/
int is_divisible_by_3_lsb(char *input) {
unsigned value = 0;
unsigned mask = 1;
char *p = input;
while (*p) {
if (*p != ',') {
if (*p == '1') {
value &= mask;
}
mask <<= 1;
}
p++;
}
return (value % 3 == 0) ? 1 : 0;
}
Personally I have a hard time believing one of these will be significantly different to the other.
I think Nathan Fellman is on the right track for part a and b (except b needs an extra piece of state: you need to keep track of if your digit position is odd or even).
I think the trick for part C is negating the last value at each step. I.e. 0 goes to 0, 1 goes to 2 and 2 goes to 1.
A number is divisible by 3 if the sum of it's digits is divisible by 3.
So you can add the digits and get the sum:
if the sum is greater or equal to 10 use the same method
if it's 3, 6, 9 then it is divisible
if the sum is different than 3, 6, 9 then it's not divisible