Having Fun with XOR (exclusive-or)

Having Fun with XOR (exclusive-or)

Jacob Sorber

2 года назад

14,013 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@Hotdog718
@Hotdog718 - 26.04.2022 19:18

x ^= y;
y ^= x;
x ^= y;

Ответить
@spark_coder
@spark_coder - 26.04.2022 19:44

Although the XOR method would be faster (I believe) because it is a bitwise operation, this seems to be an easier to grasp solution for beginners
(although XOR is better for learning the fundamentals of computer science)

x = x + y; // x = (x + y)
y = x - y; // y = (x + y) - y = x (remember this for the next step)
x = x - y; // x = (x + y) - x = y

... TaDa ...

Ответить
@unperrier5998
@unperrier5998 - 26.04.2022 20:12

In x86 assembly we used to use XOR to zero a register without having to incur a memory fetch.
More recent CPU have a way to zero a register, for example sparc has the zero register which is hardcoded to 0x0 inside the CPU logic.

Ответить
@mgx9383
@mgx9383 - 26.04.2022 22:02

This is what I came up with on paper:
x = x NXOR y
y = x NXOR y
x = x NXOR y
But I guess there's a simpler way.
Edit: Well, negation is unnecessary.

Ответить
@Uerdue
@Uerdue - 26.04.2022 22:48

asm ("xchg %0, %1;" : "+r"(x), "+r"(y));

Ответить
@steffenpo
@steffenpo - 26.04.2022 22:49

Boah... well, even for me as an IT and elecronitc guy for many years... Well, i knew what XOR is used for an i did use it alot for stuff like digital input signal changes detection and stuff but i never ever thought about using it to swap integer values around.

Well if i think about it with some C type casting it is possible to swap pointers and floats around...

Ответить
@lorensims4846
@lorensims4846 - 26.04.2022 22:52

Every time I see this I think about a comic (strip?) I saw in the early eighties rthat referenced a (tech) wizard with the name of "Exorandandor."

Ответить
@IamTheHolypumpkin
@IamTheHolypumpkin - 26.04.2022 22:59

I learned to understand binary operators and boolean algebra by playing around with minecraft redstone.

Ответить
@obeid_s
@obeid_s - 26.04.2022 22:59

I love the bits (byte) and i dont have degree, so i had to learn the hard way, i decided to write webSocket so i can encode the message, i saw the frame, tried to understand it, and now i'm kinda 70% learned how to deal with bytes and charsets ..
BUT.. its the first time i know from you, that i can swap with XOR .. lol
So Thank you.. hope u hit 100K soon.

Ответить
@Uerdue
@Uerdue - 26.04.2022 23:40

Assuming x and y are 32-bit integers, placed immediately next to each other in memory, with y having the lower address:
asm ("rolq $32, %0;" : "+m"(y));
(Interprets x and y as one 64-bit number and rotates that by 32 bit, i.e. shifts it 32 bit to the left with those bits that would be shifted out on the left being shifted back in on the right.)

Ответить
@Mnogojazyk
@Mnogojazyk - 27.04.2022 00:09

Well, I like it but I can’t admit to understanding it.

Ответить
@n0kodoko143
@n0kodoko143 - 27.04.2022 00:57

Pre-answer (before finishing video):

X=&y
*X
Y=&x
*Y

Ответить
@rustycherkas8229
@rustycherkas8229 - 27.04.2022 02:43

Interesting timing!
Before I knew it was "hashing", I sought to improve a loop whose purpose was to translate (English) month names to integers. ( "December" -> 12 ) Turns out adding the 2nd & 3rd letter of each month 'hashes' to unique values that could ( & 0x1F ) index into a 32 byte translation table.


Recently mucking with improving that, I discovered 12 unique values could result from a different hash function involving XOR.

Here's my gift to the world:
int monthOrd( char cp[ ] ) {
return "EA@BIC@KJ@DHGF@L"[ ((cp[0]<<1) + (cp[1]+1) ^ (cp[2]>>1)) & 0xF ] - '@';
}
Give it a string like "September" or "Oct" and it will give you the month's ordinal (with a lot of false positives!) Now that the caller knows which month (1-12), the caller can test the input is a valid name of a specific month (ie: not "Octopus"). A lot faster than making up-to 12 guesses with strcmp(). (And, yes, this is case insensitive... "JAN" or "January" or "jan" all return '1' .)

(The application of this is a lot more specific than De Bruijn's algorithm, but it's been a fun coding challenge to write the program that attempts various hashing functions searching for one that gives the desired results (12 unique hashes in a range of 0-15)...)

Cheers!

Ответить
@trentlangford9050
@trentlangford9050 - 27.04.2022 04:19

The fact that XOR is essentially its own mathematical inverse is very interesting and very useful. This was an interesting video!

Ответить
@kaushaljani6769
@kaushaljani6769 - 27.04.2022 09:15

If sum of value does not exceeds limit
Then
X=x+y
Y=x-y. // It becomes x
X=x-y // x+y - x hence y

Ответить
@justwatching6118
@justwatching6118 - 27.04.2022 17:01

Cool! :)

Ответить
@smrtfasizmu6161
@smrtfasizmu6161 - 27.04.2022 21:08

I don't know for others but I like the content about encryption such as the one that Ben Eater has made.

Ответить
@elclippo4182
@elclippo4182 - 27.04.2022 21:47

XOR is the friend of every encryption algorithm.

Ответить
@rogo7330
@rogo7330 - 28.04.2022 00:01

I once come up with xor-swap for myself when i remembered that basically we can via xor put numbers on each over and then remove them out of this mess. I was even proud of myself, lol)
(A, B); (A^B, B); (A^B, A^B^B) = (A^B, A); (A^B^A, A) = (B, A)

Ответить
@skilz8098
@skilz8098 - 28.04.2022 02:40

If you want to know more about the XOR operator, just look at the XOR Truth Table within Boolean Algebra, then check out the how an actual XOR Gate works within a circuit. Then any functions that use bitwise logical operators such as ^, will become much more clearer to what is happening within the function and why XOR is being used. It is simple to understand, it is fast and cheap. These types of operators typically work at the register level unless they have to fetch the values from either cache, ram or some other memory device. I'm 100% self taught, and from my own personal learning experience is that if you can not understand XOR then why are you even writing source code or programming in the first place? All it is is bit manipulation through bit comparison.

Here's a couple of tables to make things simple:

XOR Truth Table:
A | B | O
------------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
==========================
Swapping Two Values:

Integer Value | 8 Bit or 1 Byte Binary Representation
A = 5 0000 0101
B = 12 0000 1100
==========================
A ^= B (A) 0000 0101 (5)
(B) 0000 1100 (12)
-----------------
A --> (9) (A) 0000 1001 (9)
---------------------------------------------------
B ^= A (B) 0000 1100 (12)
(A) 0000 1001 (9)
-----------------
B --> (5) (B) 0000 0101 (5)
---------------------------------------------------
A ^= B (A) 0000 1001 (9)
(B) 0000 0101 (5)
-----------------
A --> (12) (A) 0000 1100 (12)
==========================
A = 12
B = 5

However this only works on integral types such as int, signed, unsigned, bool, char. To swap floating point values a temporary in most cases must be used due to how floating point values are stored in memory.

XOR is a powerful tool and should never be frowned upon just cause the syntax might look confusing. Learn the instruction set, its functionalities and capabilities before trying to programming a device!

I have no formal education but I've been an independent study and hobbyist who's used C,C++,C# and a couple of other languages were my interests are within 3D Graphics Engine Design, Physics Simulation, Audio Processing, Animation, Hardware Emulation, and more. There is nothing wrong with the use of XOR!!!

This is my own opinion from my own experiences. I don't shy away from the use of bitwise logic or arithmetic operators where others may call it bit twiddling or bit hacking...

Ответить
@EvilSapphireR
@EvilSapphireR - 28.04.2022 22:26

x=x+y
y=x-y //y now holds the value of old x
x=x-y //x now holds the value of old y

Lol.

Ответить
@redcrafterlppa303
@redcrafterlppa303 - 29.04.2022 08:27

Do you know what sizes the t-shirts at merchonate are? Is there an American standard for s, m, l...? I'm from Europe and here every shop usually has their own measuring chart. Thanks in advance

Ответить
@vk3fbab
@vk3fbab - 29.04.2022 15:03

I remember years ago struggling with a SQL query. It looked simple but I couldn't get it to give the correct results. Ended up making a truth table and it ended up being XOR. So wrote XOR into my query and it passed all of the tests. Probably not efficient and had lots of comments explaining what was going on.

Ответить
@billowen3285
@billowen3285 - 29.04.2022 16:00

Will people look at me strangely if I say ‘Zor’? It just seems more natural

Ответить
@raj_c
@raj_c - 01.05.2022 09:51

Hi when you will offer embedded system course

Ответить
@cgln8760
@cgln8760 - 01.05.2022 12:55

Xor is used by disk controllers to recreate missing missing data in a RAID 5 array, in a raid array with 4 data disks and one parity disk, the parity disk is created by Xoring the data of the 4 data disks, then if any one disk fails (including the parity disk) the missing data is recreated by xoring the data on all remaining disks, this can be used in real time and also to rebuild the new disk that replaces the failed disk.

Ответить
@makealemonade
@makealemonade - 01.05.2022 20:33

Careful there! Check for the case when x == y, don’t do xor when x == y since it will make it 0.

Ответить
@makealemonade
@makealemonade - 01.05.2022 20:34

Careful there!! Check for the case when x == y, don’t do xor when x == y since it will make it zero.

Ответить
@AlexJacksonSmith
@AlexJacksonSmith - 02.05.2022 16:13

This is like a one-time-pad logic to move values...

Ответить
@unclerojelio6320
@unclerojelio6320 - 05.05.2022 03:00

XOR is used for Linear Feedback Shift Registers as well.

Ответить
@KTegoshi
@KTegoshi - 05.05.2022 15:43

oh fascinating. i only know of the address swap technique to do this

Ответить
@MrSRIVATSABR
@MrSRIVATSABR - 05.05.2022 17:12

y = ((x ^ y) ^ (x = y)); Hey Jacob, I tried something like this and it works ! :)

Ответить
@sivaramd5637
@sivaramd5637 - 16.05.2022 07:04

We also swap them using sub and add operator instead of xor:
x = x - y;
y = y + x;
x = y - x;

Ответить
@AnyVideo999
@AnyVideo999 - 26.05.2022 22:17

XOR is much better off though of as addition where 1 represents all odd numbers and zero represents all even numbers. Then everything becomes very intuitive from the rules of addition we are accustomed to.

Ответить
@fordfactor
@fordfactor - 29.05.2022 12:40

I recall using XOR logic to implement a selection rectangle that highlights what you select when you click and drag your mouse pointer over an image. An XOR converts the image pixels to the rectangle colour, and then a subsequent XOR changes it back to the original colour if the selection rectangle changes.

Ответить
@mohammedsamir5142
@mohammedsamir5142 - 11.06.2022 19:29

Use xor to toggle a flag instead of using if statements or even the ternary operator.

bool flag = 1;
flag ^= 1; // toggle between true and false

Bonus: we can also use addition + and subtraction - to swap x and y.

Ответить
@danilomitrovic3954
@danilomitrovic3954 - 14.06.2022 16:10

To all, this doesn't work with python with negative numbers. Python works with specific format to represent negative numbers that uses XOR. Results may wary 🤷

Ответить
@kz_cbble9670
@kz_cbble9670 - 15.10.2022 15:45

X=x+y
Y=x-y
X=x-y

Ответить
@YilmazDurmaz
@YilmazDurmaz - 06.11.2022 21:31

there is another similar one (no temp) but with addition/subtraction, provided that the total will stay in the range:
x = x+y // x=a+b
y = x-y // y=a
x = x-y // x=b

Ответить
@FelixNielsen
@FelixNielsen - 12.11.2022 20:50

That was some rather limited XOR fun. I had high hopes, as I
m a sucker for bit twiddling, so more please.

Ответить
@sharpfang
@sharpfang - 27.11.2022 00:06

gawd. chaining assignments, x ^= y ^= x ^= y;

Ответить
@Nyall
@Nyall - 17.12.2022 06:19

I used to do a lot of 68k assembly, which is a 32bit processor. Here's something I thought of to left shift a 64bit integer in two regisers d0, d1, by a value in d2. It destroys d3. Output is in d0 and d1

d3 = d1 // make a copy of the lower 32 bits into d3.
d0 = d0 shifted left by d2 // left shift the upper 32 bits, but moves in zeros for the LSBs.
d1 = d1 shifted left by d2 // left shift the lower 32 bits.
d3 = d3 rotated left by d2 // rotate the lower 32 bits
d0 = d0 xor d3 // fill in the LSBs of the upper 32 bits of the result, but this modifies the MSBs of the upper 32 bits.
d0 = d0 xor d1 // un-modify the MSBs

Ответить
@angelcaru
@angelcaru - 01.01.2023 19:20

// (x ^ y) ^ y = x
// (x ^ y) ^ x = y

x ^= y; // x = (x ^ y)
y ^= x; // y = x
x ^= y; // x = y

Ответить
@streakz6595
@streakz6595 - 02.02.2023 23:39

The solution I found is pretty simple (and it doesn't involve bitwise operations):
x -= y;
y += x;
x = -(x-y);

Ответить
@69k_gold
@69k_gold - 19.03.2023 08:19

It's important to remember that this only works on chars, long longs, longs, ints and shorts. IEEE-754 forbids XOR operation on floats and doubles

Ответить
@samplesandtests
@samplesandtests - 29.04.2023 01:23

i wonder if it can be done in assembly (on some processor) to swap the values in registers, without using any ram. i don't think it can be done in x86 assembly and i don't think 6502 assembly has a xor opcode.

Ответить
@SouravTechLabs
@SouravTechLabs - 05.05.2023 08:26

Unfortunately throughout my entire programming career, I never had to swap two variables :( Maybe I am unlucky...
But - I use XOR for one thing for sure, and it's handy. Consider this:

i = 0
# toggle some flags to true - false or 0 - 1
i = i == 0 ? 1 : 0

This toggles i every time. Say you want to toggle light on an off with an Arduino or something like that.

Now the whole thing can be just replaced with:
i = 0
i ^= 1

This is the thing I need a lot, like a lot of times. And there are other usages too. I knew the variable swap stuff, but just never needed it. It's good for cryptographical stuff mostly.

Ответить
@LettersAndNumbers300
@LettersAndNumbers300 - 20.07.2023 19:16

My fav Google interview question: you have an array of integers where every number in it occurs an even number of times except for one number. What is the optimal way to find it?

Ответить