Why Int8.max &+ Int8.max equals to "-2"? - swift

Following Swift Standard Library documentation, &+ discards any bits that overflow the fixed width of the integer type. I just did not get why adding two maximum values, 8-bit signed integer can hold results in -2:
/// Two max Int8 values (127 each, 8-bit group)
let x6 = Int8.max
let x7 = Int8.max
/// Prints `1 1 1 1 1 1 1`
String(Int8.max, radix: 2)
/// Here we get `-2` in decimal system
let x8 = x6 &+ x7
/// Prints `-1 0`
String(x8, radix: 2)
If we break down the binary calculation we will get this:
1 1 1 1 1 1 1
+ 1 1 1 1 1 1 1
-----------------------------
1 1 1 1 1 1 1 0
Which is -126, as the leftmost bit is a negative sign.
Why does Swift discards any bits except the rightmost two (1 and 0). Did I miss some overflow rules? I've read some pieces of knowledge in the web, but did not get closed to cracking this one.

Swift (and every other programming language I know) uses 2's complement to represent signed integers, rather than sign-and-magnitude as you seem to assume.
In the 2's complement representation, the leftmost 1 does not represent "a negative sign". You can think of it as representing -128, so the Int8 value of -2 would be represented as 1111 1110 (-128 + 64 + 32 + 16 + 8 + 4 + 2).
OTOH, -126 would be represented as 1000 0010 (-128 + 2).

Related

How can I convert binary bits into index in MATLAB

I have a question regarding how to use the binary bits as an index in MATLAB, For example, if I'm using 4 antennas to transmit data, in each instant, one antenna or two are active to transmit the data. how can I use the indexing of antennas to transmit that symbol, here an example as below:
%Suppose I'm using for antennas to transmit that data.
Nt = 4; % Number of antennas
Symbole = 1+j; % The symbol to transmit in binary after modulation
Ant_index = 11; % The antenna index which will be used to transmit data. (here number 3 will be used)
x_trans =zeros(Nt,1); % Initialization of antennas
x_trans(Ant_index) = Symbole; %Use the antenna to transmit the data
My question is in the last step, x_trans(Ant_index) = Symbole;I want to use the binary bits as index, which means, instead of the bits Ant_index = 11 which means 3 in decimal, I want to use the two bits as antennas for transmitting the same symbol. for example if I have bits 0101 , It means I will use the antenna number 1 and number 3 to transmit the symbol in the same above example Ant_index = 0011. it means that first and second antennas will be used to transmit the Symbol.
EDIT:
Second part of question, what's about if the generated bits for antenna indexing are generated randomly. and we want to avoid having the Ant_index = 000; in other words, we need the Ant_index to be as decimal value, and then make mapping for 000 which is in decimal 0, the antenna 1 should be activated, 001 = 1 ---> antenna 2 should be activated. 010 = 2 ---> antenna 3 active, 011 = 3 ---> antenna 4 active. 100 = 4 ---> antennas 1 and 2 are active, 101 = 5 ---> antennas 1 and 3 are active, and so on.
Depending on the desired format of your input, you can use one of the 2 decimal to binary conversion function:
de2bi => return
an array of 0 and 1, representing the binary number.
dec2bin =>
return a string representation of the binary number.
Conversion:
I recommend using de2bi since an array will be easier to convert into indices. For example:
activate antenna 1 and 2 (3 decimal == 11 in binary):
>> de2bi(3) % index antenna 1 and 2 (`3` decimal == `11` in binary):
ans =
1 1
>> de2bi(10) % index antenna 2 and 4 (`10` decimal == `1010` in binary):
ans =
0 1 0 1
Note that by default de2bi return the binary representation in small endian bit ordering (the first element in the array represents the lowest bit). This is a bit the opposite of our visual convention, there is a parameter to reverse that, but for your purpose it is already exactly what we want. It saves us from reading the array from right to left or reversing it.
Indexing:
You said you have 4 antenna, but for this example I'll enlarge that a bit. Let's say you need to control 7 antenna. It would mean I always have to have an array of indices conataining 7 elements. No problem, de2bi allows you to specifiy the number of output digits. So again, to activate antenna 2 and 4 (out of seven):
>> Nt=7;
>> Ant_index = de2bi(10,Nt)
Ant_index =
0 1 0 1 0 0 0
with that you can directly use your index to transmit data:
x_trans(Ant_index) = Symbole;
Input format:
This is all and well if you know your elementary binary table up to your number of antenna. In case you want to be able to specify active antennas with a binary representation instead of a direct decimal number, you can use the reverse conversion function, more specifically bin2dec
So a last example to show you how they all work together:
>> stringAntIndex = '1010'
stringAntIndex =
1010
decimalAntIndex = bin2dec(stringAntIndex)
decimalAntIndex =
10
>> Ant_index = de2bi(decimalAntIndex,7)
Ant_index =
0 1 0 1 0 0 0
Which of course you could simplify to:
>> stringAntIndex = '1010' ;
>> Ant_index = de2bi(bin2dec(stringAntIndex),Nt)
Ant_index =
0 1 0 1 0 0 0
Edit: Ok I place the answer to your updated question here to finish it but note that your edited question is completely different than your original question. What you are asking now has nothing to do with converting bits into indices, it is just a straight mapping which you have to define before hand (since it doesn't follow any computation logic).
Basically, store your active antenna indices in a cell array, and pick the the cell corresponding to your randomly generated index (you'll have to add 1 because MATLAB starts array indices at 1, not at 0 like many other languages.
So:
% Map the antenna to be active depending on decimal input
Antenna2Activate = {
[1] ; % antenna 1 active
[2] ; % antenna 2 active
[3] ; % ...
[4] ; % ...
[1 2] ; % antenna 1 & 2 active
[1 3] ; % antenna 1 & 3 active
[1 4] ; % ...
[2 3] % antenna 2 & 3 active
};
% Then to activate the proper antenna given a decimal input [decimalInput]:
Ant_index = Antenna2Activate{ decimalInput+1 } ;
x_trans(Ant_index) = Symbole;
To make sure it works the way you want, you can run the following code:
decinput = 0:7 ;
for k=1:numel(Antenna2Activate)
Ant_index = Antenna2Activate{ decinput(k)+1 } ;
fprintf('Decimal input= %d \t Binary= %3s \t Ant_index: ',decinput(k),dec2bin(decinput(k),3))
disp(Ant_index)
end
Which yields:
Decimal input= 0 Binary= 000 Ant_index: 1
Decimal input= 1 Binary= 001 Ant_index: 2
Decimal input= 2 Binary= 010 Ant_index: 3
Decimal input= 3 Binary= 011 Ant_index: 4
Decimal input= 4 Binary= 100 Ant_index: 1 2
Decimal input= 5 Binary= 101 Ant_index: 1 3
Decimal input= 6 Binary= 110 Ant_index: 1 4
Decimal input= 7 Binary= 111 Ant_index: 2 3
You do ant_index = [0,0,1,1] for transmitting the symbol on antenna 1 and 2. Then do x_trans(ant_index == 1) = symbol. Hope that helps.

How to modify the last 3 bits of signed numbers

When I apply the function dwt2() on an image, I get the four subband coefficients. By choosing any of the four subbands, I work with a 2D matrix of signed numbers.
In each value of this matrix I want to embed 3 bits of information, i.e., the numbers 0 to 7 in decimal, in the last 3 least significant bits. However, I don't know how to do that when I deal with negative numbers. How can I modify the coefficients?
First of all, you want to use an Integer Wavelet Transform, so you only have to deal with integers. This will allow you a lossless transformation between the two spaces without having to round float numbers.
Embedding bits in integers is a straightforward problem for binary operations. Generally, you want to use the pattern
(number AND mask) OR bits
The bitwise AND operation clears out the desired bits of number, which are specified by mask. For example, if number is an 8-bit number and we want to zero out the last 3 bits, we'll use the mask 11111000. After the desired bits of our number have been cleared, we can substitute them for the bits we want to embed using the bitwise OR operation.
Next, you need to know how signed numbers are represented in binary. Make sure you read the two's complement section. We can see that if we want to clear out the last 3 bits, we want to use the mask ...11111000, which is always -8. This is regardless of whether we're using 8, 16, 32 or 64 bits to represent our signed numbers. Generally, if you want to clear the last k bits of a signed number, your mask must be -2^k.
Let's put everything together with a simple example. First, we generate some numbers for our coefficient subband and embedding bitstream. Since the coefficient values can take any value in [-510, 510], we'll use 'int16' for the operations. The bitstream is an array of numbers in the range [0, 7], since that's the range of [000, 111] in decimal.
>> rng(4)
>> coeffs = randi(1021, [4 4]) - 511
coeffs =
477 202 -252 371
48 -290 -67 494
483 486 285 -343
219 -504 -309 99
>> bitstream = randi(8, [1 10]) - 1
bitstream =
0 3 0 7 3 7 6 6 1 0
We embed our bitstream by overwriting the necessary coefficients.
>> coeffs(1:numel(bitstream)) = bitor(bitand(coeffs(1:numel(bitstream)), -8, 'int16'), bitstream, 'int16')
coeffs =
472 203 -255 371
51 -289 -72 494
480 486 285 -343
223 -498 -309 99
We can then extract our bitstream by using the simple mask ...00000111 = 7.
>> bitand(coeffs(1:numel(bitstream)), 7, 'int16')
ans =
0 3 0 7 3 7 6 6 1 0

Hex Twos Complement Arithmetic

I'm trying to do the following problem:
E8B2035D
-FB60528D
----------
In which, the integers represented are hex representations of 32-bit two's compliment binary numbers. What is the best approach to solve this problem, and detect overflow?
Subtraction becomes addition when you use two's complement. So I would take the complement of the second number, then add them:
As you know, the two's complement of a number starts out by turning every 1 into 0 and vice versa (handy rule of thumb: do 15 - number, so F -> 0, E -> 1, D -> 2, etc):
FB60528D --> 049FAD72
Then add one to the number (in this case, 2 + 1 = 3, and there is no carry):
049FAD73 -- the two's complement of FB60528D
Now we add the numbers, using conventional rules of addition:
E8B2035D
049FAD73 +
----------
D + 3 = 10 : write 0, carry 1
1 + 5 + 7 : write D, carry 0
3 + D = 10 : write 0, carry 1
1 + 0 + A : write B, carry 0
2 + F : write 1, carry 1
1 + B + 9 : write 5, carry 1
1 + 8 + 4 : write D, carry 0
E + 0 : write E
The final result (still in two's complement) is
ED51B0D0
You would detect overflow if the last calculation resulted in a carry (a number > F).

Output in Vector form

I am getting output of reshape function as follow
s1 =
11
00
10
11
01
11
10
10
10
10
10
10
10
01
10
01
How to convert s1 as
[1 1 0 0 1 0 1 1 0 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0 1 1 0 0 1]
so i can pick up bit values
s1(1) will be 1
s1(3) will be 0
s1(5) will be 1
I have tried it with reshape and transpose but not picking up correct bit values. Appreciate any help..
I am doing following operation with below code
converting cipher text to bytes, then I am calculating index variable (called as p) & formula is MOD(No of Bytes,3).. I have ciphertext length as 5 bytes so Index Variable (p) is 2.. I will always have index varaible values as 0 or 1 or 2 which will be based on no. of Bytes
Say ciphertext is 11001011 01111010 10101010 10011001 01010101
This data is five bytes there for inde variable is 2
11001011 01111010 10101010 10011001 01010101
Now
for first two bits (11) , index variable to be assigned as 2
for next two bits (00), index variable to be assigned as 0
for next two bits (10), index variable to be assigned as 1
for next two bits (11), index variable to be assigned as 2..so on till end of my bits.
Other Example
Ciphertet with Three Bytes 11001011 01111010 10101010
Index Variable (p) will be 0
for first two bits (11) , index variable to be assigned as 0
for next two bits (00), index variable to be assigned as 1
for next two bits (10), index variable to be assigned as 2
for next two bits (11), index variable to be assigned as 0..
so on till end of my bits..
s = '11001011 01111010 10101010 10011001 01010101'
p = rem(numel(regexp(s,' [01]'))+1,3)
k = (0:2)'
s1 = reshape(regexprep(s,' ',''),2,[])'
n = size(s1,1)
N = k(:,ones(fix((n+1)/3)+1,1))
P = N(find(N(:,1) == p)+(0:n-1))'
Well s1' will give you
[11 00 10 11 ...]
but if you show us the input to your function I might be able to give you the answer you really want.
The key to this question is that the elements are of char type. Then you could use reshape like this:
reshape(s1.',1, [])
ans = 11001011...
This is a similar question.

What Is The Purpose of Negative Modulus Operator Results?

I was previously under the (naive) assumption that the modulus operator returned the remainder of division. I was apparently wrong, as -2 % 5 returns 3. I would have thought that 5 divides -2 zero times with -2 as the remainder.
Now I understand the mechanics of how this operation is performed, but my question is why? Could someone give me a link to something that explains why modulus and remainder are not synonymous, or an example of a situation where it would be useful?
The result is entirely correct. Modular arithmetic defines the following (I'll use "congruent" since I can't type the equal sign with three lines)
a congruent b mod c iff a-b is a multiple of c, i.e. x * c = (a-b) for some integer x.
E.g.
0 congruent 0 mod 5 (0 * 5 = 0-0)
1 congruent 1 mod 5 (0 * 5 = 1-1)
2 congruent 2 mod 5 (0 * 5 = 2-2)
3 congruent 3 mod 5 (0 * 5 = 3-3)
4 congruent 4 mod 5 (0 * 5 = 4-4)
5 congruent 0 mod 5 (1 * 5 = 5-0)
6 congruent 1 mod 5 (1 * 5 = 6-1)
...
The same can be extended to negative integers:
-1 congruent 4 mod 5 (-1 * 5 = -1-4)
-2 congruent 3 mod 5 (-1 * 5 = -2-3)
-3 congruent 2 mod 5 (-1 * 5 = -3-2)
-4 congruent 1 mod 5 (-1 * 5 = -4-1)
-5 congruent 5 mod 5 (-1 * 5 = -5-0)
-6 congruent 4 mod 5 (-2 * 5 = -6-4)
-7 congruent 3 mod 5 (-2 * 5 = -7-3)
...
As you can see, a lot of integers are congruent 3 mod 5:
..., -12, -7, -2, 3, 8, 13, ...
In mathematics, the set of these numbers is called the equivalence class induced by the equivalence relation "congruence". Our understanding of the remainder and the definition of the "mod" function are based on this equivalence class. The "remainder" or the result of a mod computation is a representative element of the equivalence class. By declaration we have chosen the smallest non-negative element (so -2 is not a valid candidate).
So when you read -2 mod 5 = x this translates to "Find the smallest non-negative x so that there exists an integer y with y * 5 = -2 - x", in concordance with the definition of congruence. The solution is y=1 and x = 3 as you can see by simply trying out other values for y.
a = n (mod m) is defined as a = n + m*t and it applies to negative numbers equally well. (Another to look at it is that a = n (mod m) means (a - n) is a multiple of m)
-2 = 3 (mod 5) because -2 = 3 - 5 (i.e. t = -1)
The convention is that the result of taking a modulo m is a number between 0 and m - 1 (inclusive)
The fundamental guarantee that you get is that
(a % b) + b * (a / b) == a
For signed values, there is no reason either sign should be the preferred outcome of a modulo or divide operation. Some languages fix one form, others leave it up to the implementation, so that the implementation can use whichever way the hardware happens to provide. The hardware instruction, in turn, may have been chosen to operate efficiently the hardware's representation of signed integers.
Generally, be very careful when using signed integers together with division, remainder and bit shift operations.
I guess it depends on whether you want your result rounded down or rounded towards 0:
2 / 5 = 0.4 = 5*0 + 2 works in both cases, whereas
-2 / 5 = -0.4 = 5*0 + -2 if you're rounding towards 0 (truncation),
-2 / 5 = -0.4 = 5*-1 + 3 if you're rounding down (floor).
Note that the result is always positive (for a positive divisor) in the second case and it would be useful, for example, when calculating an array index:
hashmapBuckets[getIntHash(obj) % hashmapBuckets.size].add(obj)
or normalizing an angle:
angle = angle % 360; //0-359
It is in fact the other case I'm having trouble finding practical examples for :)
--
Oh, and the Wikipedia page on the modulo operation has some nice graphs. Note that the remainder always has the same sign as the divisor for a floored division.
Think of modulo as an operator that wraps a line of length y (in terms of y % x) around a circle of x pegs. The remaining length of the line that doesn't fully wrap around x is the resultant.