Question:

Is there a way to typecast ints to arrays?

by  |  earlier

0 LIKES UnLike

I'm writing a program in C++ and I need to write a function that looks at all the digits in a long number (integer type, though--maybe 6 digits) and can compare each digit.

There are some really sloppy ways to do this with modulus (%) but I'm hoping there's a way to typecast the number as an array of chars, one digit per entry in the array?

Do you know how I can look at the digits separately?

 Tags:

   Report

2 ANSWERS


  1. You are thinking about this backwards. To the computer, the number 321 is not three digits. It's a quantity that can be expressed by three digits in base 10 if you want, but is at root simply a quantity.

    You cannot cast it to an array of chars because these are two fundamentally different things. The character sequence '3', '2', '1', is very different from the numerical result of adding three hundreds to two tens and one unit.

    Using modulus and other operations to manipulate the numerical quantity into base-10 digits is the correct way.

    To a computer, that 321 is 3 hundreds, 2 tens, and one unit is no more special than that it's 5 64's and 1 unit, or 2 144s, 2 12s, and 9 units.


  2. Print its decimal value into a string (char array), then examine each char of the array.

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.