DEV Community

Laiba
Laiba

Posted on

πŸ•΅οΈβ€β™‚οΈ The Case of the Vanishing Digits: Why 123,456 = 64?

Ever had a piece of code do something so weird you thought your computer was possessed? πŸ‘»

Check out this C++ mystery:

char ch = 123456;
cout << (int)ch; 
// Output: 64 🀯
Enter fullscreen mode Exit fullscreen mode

That is a great idea! Acknowledging the mentors who helped you understand a concept adds a nice personal touch and builds community. Since you're currently working through his DBMS playlist and following his roadmap, it fits perfectly.

Here is the updated version with a "Shoutout" section included at the end:


πŸ•΅οΈβ€β™‚οΈ The Case of the Vanishing Digits: Why 123,456 = 64?

Ever had a piece of code do something so weird you thought your computer was possessed? πŸ‘»

Check out this C++ mystery:

char ch = 123456;
cout << (int)ch; 
// Output: 64 🀯
Enter fullscreen mode Exit fullscreen mode

Wait... what? Where did the other 123,392 go? Did the compiler steal them? πŸ’Έ

Actually, it’s all about "The Teacup Rule." β˜•


1. The Container Problem πŸ“¦

Think of a char as a tiny teacup. It can only hold 8 bits of data.

The number 123,456 is like a gallon of water. When you try to pour a gallon into a teacup, you don't get a gallon-sized teacup... you just get a mess on the floor and a very full cup.

2. The "Binary Guillotine" βœ‚οΈ

Computers see numbers in binary (1s and 0s). Let’s look at what happened under the hood:

  • 123,456 in binary is: 1 11100010 01000000 (17 bits long!)
  • A char only has room for the last 8 bits.

So, C++ acts like a guillotine and chops off everything that doesn't fit:
❌ Discarded: 1 11100010
βœ… Kept: 01000000

3. The Math Magic ✨

When we translate those leftover bits (01000000) back into a decimal number, we get:
$2^6 = 64$

That’s why your output is 64! The computer didn't make a mistake; it just followed your instructions to squeeze a giant into a tiny box. 🧳


πŸ’‘ The Takeaway

This is called Data Truncation. It’s a classic "gotcha" in programming.

Pro-Tip: If you’re expecting big numbers, stay away from char. Use int or long long instead! Otherwise, your data might just "overflow" onto the floor. 🌊


πŸ™Œ A Special Shoutout

I want to give a huge thanks to Love Babbar! πŸš€ His amazing teaching style and structured roadmaps have been a massive help in my journey of mastering these foundational concepts. If you're diving into DSA or DBMS, his content is a goldmine!


πŸ› οΈ Quick Challenge

If you change the code to cout << ch; (without the int part), you’ll see the @ symbol. Why? Because 64 is the ASCII code for the @ sign! πŸ“§

Have you ever run into a bug where your numbers mysteriously changed? Let me know in the comments! πŸ‘‡

Top comments (0)