Hacker News new | ask | show | jobs
by thaumasiotes 1514 days ago
> For example, if Int8 = -10 and UInt16 = 5, and I’m expecting an answer of -5, then I’ll need to be more explicit to get the number I’m looking for. If I’m expecting [65531], then the implicit promotion works fine.

That depends on what you're hoping to do with the number you're looking for. If you wanted -5 as an Int16, the bit pattern would be 1111 1111 1111 1011 or 0xFFFB.

If you wanted 65531 as a UInt16, the bit pattern for that is 1111 1111 1111 1011 or 0xFFFB. You're getting the same result either way. And any values you compute from that result [that is, by arithmetic] are going to be unaffected by whether you labeled the result "Int16" or "UInt16", because that's just a label. If you labeled 0xFFFB a "Snerf", the arithmetic would still be the same.

There are only a very restricted set of places where you need to be explicit about whether you think of your variable as an Int or a UInt:

1. When you're widening it.

2. When you're doing a right shift.

3. When you're formatting it for display to a human.

1 comments

Yeah, case three was the one I was thinking of, though cases one and two are interesting as well. Number two requires you to think about using an arithmetic or logical right shift, though I'm struggling to think of a situation where you'd be promoting types and then not know what your intent was if you're then doing a right shift. I guess my confusion here is simply related to the idea that if you're getting that deep into binary, you'd probably want to be more explicit about what types you want to promote to, rather than relying on the Julia defaults. It's been a while since I've needed to think deeply about bitwise operations, still just as interesting as I remember.