Sorry, I didn't add any text to the post lol. Code itself shouldn't be that bad but the purpose is pretty awful. I'm passing commands to a microcontroller and using a two byte hash of the name of the command in the serialisation. I don't want to deal with collisions so I just run this check on the whole codebase to see if literally any two words end up having the same hash, and then just don't use them as command strings.
Code itself is lovely and unpythonic but I think for a tiny script it doesn't really matter
The only purpose of this is to see if literally any words in my codebase have the same hash, so I don't need to do anything further with the information. My plan is to just not deal with collisions in the application and instead run this script periodically to make sure I'm not using any forbidden words lol
Then I don't see any purpose in using hash. You can just have a list of forbidden words and check if any word from your code is in the list. In that case you can avoid situations when word is not forbidden, but has the same hash value.
I'm using that specific hash function in the application to encode command IDs that get send to an MCU. In order to avoid having to deal with clashing command IDs on the MCU side, I'm manually checking all my words to avoid that situation occurring
I guess there's a few reasons. Firstly, I only want two bytes of my packet dedicated to the id. Secondly, I can make my hash function constexpr and on the MCU side do things like:
switch(id)
{
case hash("command1"):
/* Do stuff*/
}
instead of creating stuff in memory.
Also my data source comes from another program and language entirely and uses strings to distinguish types of commands, so I need some kind of interface I control on a low level anyway.
Why do you need a hash then? Sounds like you’re basically hard coding a mapping from 0-65535 to words but with extra steps. Is there something you gain from assigning them to unique hashes instead of a serial ordering?
Yeah that mapping is all I need! Not exactly cure what my extra steps are, or what a serial mapping is. Do you mean an index into an array? I've considered that, but it's just one more thing to have to keep in sync ig
So instead of sending/interpretting a hash for “command1” you just send the value “1”. You’d replace all references to hash(“command1”) with the 0x0001. Ideally, you’d define this mapping in a centralized place and use variables/macros to refer to the value 0x0001.
Ah I see. Well given that hash is constexpr, isn't that what my approach boils down to anyway, but without the hassle of keeping a mapping file somewhere?
Also (slightly beside the point) the sender side of the application is Max/MSP which is a weird visual programming language and using strings/messages is a lot more appropriate over there.
Then I don't see any purpose in using hash. You can just have a list of forbidden words and check if any word from your code is in the list. In that case you can avoid situations when word is not forbidden, but has the same hash value.
You seem to be misunderstanding what he's doing. For some reason, no word in his code can have the same hash (the one used) as another word. He is running this script to make sure a collision doesn't happen. If one does happen, he'll probably change one and make sure there is no collisions afterward.
I don't fancy complicating my serialisation so I'm going for a 'prevention is better than cure' approach to string hashing.
Edit: I don't think I provided enough context here. This isn't meant to be part of a python project, rather it's a script I run on my whole codebase (cpp) to see if my hash function I use for serialising commands will result in any clashes. I don't plan on dealing with hash collisions, so instead I have this tool to show me which words to avoid.
It's generally just making use of the individual bits in an integer. The most common use-case (for me) is multiple binary options in a single integer and it's very useful for that purpose--especially with C/low-level stuff and databases.
... Really? I can understand not really ever using bitwise operators, but you can't even understand them? It's just boolean logic (the thing that all computing is built on), but applied to multiple bits at a time.
Computing is SO vast that anyone could spend 13 years becoming an expert in something so different and unrelated to something else that is in the same field.
But, boolean logic comes up anytime you need to check more than a single condition in an if statement at a time, unless you like chaining together lots of if statements. It's not some obscure domain-specific thing that only shows up in a few specialties, it's a standard part of any CS curriculum.
bitwise operations are not JUST boolean logic. It's applying that boolean logic in a certain way that can create the confusion. In the same way in networking how subnet masks are -just- boolean logic. Logic gates can be reduced down to a combination of True False operations but that doesn't preclude the additional complexity that they can have. That's literally how computers work on a transistor level yet here we are operating something vastly more complex than a simple boolean True False lever.
Not understanding bitwise operators themselves, and struggling to understand/follow along with anything more complicated built on top of them are two different issues, though, and I'm talking entirely about the first case here. The second one is totally understandable in the same way that say, regexps are easy to learn and hard to actually work with. The first is... much more baffling, especially with 13 years of experience.
I'm not sure it's that big of a deal to not 'understand' bitwise operations. You can be totally unexposed to bitwise operations your entire career depending on what you do. I personally find regular expressions relatively easy to understand and build but I'm not gonna fault someone for not being exposed to them enough to understand their intricacies. I've met software engineers who can't diagnose IT issues, it sort of baffles me, but then I remember there's an incredible amount of knowledge out there and even if I continue to learn and study until the day I die I still won't understand even half of it.
I work in quant finance building trading systems. I am a machine learning engineer building ML models for generating trading signals at a hedge fund. Only ever done that really. Never had to use them 🤷♂️
All you gotta know for this "hash" function is they generate a numeric value into the "hash" variable, and then return it with "& 0xFFFF" which will clamp it down to a 16bit integer since 0xFFFF is 16 bits and it's a binary AND operation. You will get the lower 16 bits. Example: (0xDDDDFFFF & 0xFFFF) = 0xFFFF, (0x12345678 & 0xFFFF) = 0x5678, each nibble is 4bits. A single hex digit has the size of a nibble 4bits.
13 years as a developer and I still don't understand bitwise operators
You shouldn't have chosen a profession with work that will stress you out endlessly through confusion. It doesn't seem like you understand programming.
It doesn't stress me out at all, when I say I don't understand it, i got it during uni and I've just not had to use it since. I'm a quant at a hedge fund building machine learning models and trading systems
It doesn't stress me out at all, when I say I don't understand it, i got it during uni and I've just not had to use it since. I'm a quant at a hedge fund building machine learning models and trading systems
Doubtful you're a quant. Quants and coders are usually different people. It would also be pretty strange for a quant hedge fund not to use a low-level language and instead use C#. Your story is full of holes. The major context clue is you said you don't understand bit operations, and boy, are those simple. If you don't understand those, you basically don't understand anything about computer architecture. There are a lot of C# developers who are like that, but unfortunately for them, they never get a job at an impressive quant fund like 6 Sigma.
The badcode part is that you are trying to reinvent the wheel. Hashing is a crucial part in computer science in general. One should know that One is not smart enough to design the algorithm of a production ready hashing mechanism. Its fun to try, but you should from here on out invest time in using the correct libraries for this job. Do your hashing with hashlib.
I actually need control over the specific hash function as it gets used in multiple places on different machines, architectures and languages in the entire application.
But equally yes, you're right, I'm not smart enough to do hashing well! That's why I'm avoiding dealing with collisions by just making sure I don't have any
import re
import os
def hash16bit(string: str):
hash = 0
for ch in string:
ch = ord(ch)
hash += (hash << 5) + ch + (ch << 7)
return (hash ^ (hash >> 16)) & 0xFFFF
def main():
wordset = set()
for root, dirs, files in os.walk("."):
for file in files:
file = os.path.join(root, file)
if not os.path.isfile(file):
continue
path, ext = os.path.splitext(file)
if ext not in [".h", ".c", ".hpp", ".cpp"]:
continue
with open(file, "r") as f:
for line in f.readlines():
for word in re.split("\W+", line):
wordset.add(word)
hash2word = dict()
collisions = []
for word in wordset:
hash = hash16bit(word)
if hash in hash2word.keys():
collisions.append(f"Collision: '{word}' and '{hash2word[hash]}' have same hash ({hash})")
else:
hash2word[hash] = word
if collisions:
for collision in collisions:
print(collision)
else:
print("No collisions found :)")
if __name__ == "__main__":
main()
The purpose of this is to check whether my specific hash function (used elsewhere) is going to result in any collisions in the rest of the codebase, which is CPP!
42
u/microwavedHamster Apr 27 '23
Why is this bad code? I feel like we're missing some context here.
46
u/partoly95 Apr 27 '23
It depends on what you want to do with this dictionary, but you can just assign lists of words with the same hash value to the key.
7
u/obidavis Apr 27 '23 edited Apr 27 '23
I don't fancy complicating my serialisation so I'm going for a 'prevention is better than cure' approach to string hashing.
Edit: I don't think I provided enough context here. This isn't meant to be part of a python project, rather it's a script I run on my whole codebase (cpp) to see if my hash function I use for serialising commands will result in any clashes. I don't plan on dealing with hash collisions, so instead I have this tool to show me which words to avoid.
46
u/[deleted] Apr 27 '23
13 years as a developer and I still don't understand bitwise operators
2
u/[deleted] Apr 28 '23
The badcode part is that you are trying to reinvent the wheel. Hashing is a crucial part in computer science in general. One should know that One is not smart enough to design the algorithm of a production ready hashing mechanism. Its fun to try, but you should from here on out invest time in using the correct libraries for this job. Do your hashing with hashlib.
10
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 27 '23
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
4
u/apepenkov Apr 28 '23 edited Apr 28 '23
Python deals with hash collisions for you tho: https://imgur.com/a/yDRlnep
E: saw your comment that it's just a test for your hash func collision, got it
1
u/someone_0_0_ Apr 28 '23
The extra space in
for root, dirs, files in os.walk("."):is what's bothering me the most1
u/[deleted] Apr 28 '23
It's not even bad code. It's just simple collision check. It's just code.
1
u/connor_ohearn Apr 28 '23 edited Apr 28 '23
https://connorohearn.pieces.cloud/?p=491e4bb30c
Here is a more readable version of it with a bunch of related links.
I also went back and adjusted it to be higher performance.
1
u/kuurtjes Apr 28 '23
3
u/[deleted] Apr 27 '23 edited Apr 27 '23
[removed] — view removed comment