Define location values โ€‹โ€‹for any base

I am looking for a function that will determine the value of a place given by a number and a base. For instance,

Given:

Whole Value: 1120 Base: 10 Place: Tens place 

Must be back: 2

Does anyone know the math for this?

Edit: It is expected that the function will pass an integer, and not like the string "e328fa" or something else. Also, the return value must be numeric, so FindInPlace (60 (integer value), 16 (base), 2 (place index, 1)) should return 3.

+4
source share
5 answers

When indexing on 1 basis, the formula:

placeval = floor (number / (base ^ (place-1))) mod base

In Python:

 def FindInPlace(number, base, place): return number//base**(place-1) % base 
+3
source

If the number is already converted to an integer (i.e. base 10)

 // Supports up to base 36 char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char FindPlace(int number, int base, int digit) { if(digit < 0) return 0; // Essentially divide the number by [base] to the [digit] power for(i=0; i<digit; i++) { number /= base; } // TODO: Verify that the digit is in range of digits return digits[number % base]; } 

( 0 gives you the largest digit, 1 gives you the next digit on the right, etc.)

I returned the digit as char to use databases over 10.

Please note that if you want to allow the user to enter the desired number as โ€œ 1 place, 10 place, 100 placeโ€ or โ€œ 1 s, 16 s, 256 sโ€, you just do

 digit = log(PlaceValue, base); 

or rewrite the code

 char FindPlace(int number, int base, int digitAsBaseToAPower) { // TODO: Error checking return digits[(number / digitAsBaseToAPower) % base]; } 
+3
source
 int getPlace(float x, float place) { return (int)(x/place) % 10; } 

This works for base-10 and can handle places to the right or left of the decimal. You would use it as follows:

 place = getPlace(1120,10); otherPlace = getPlace(0.1120,1e-3); 

A more general solution for any base is difficult. I would go with a string solution.

+3
source

Something like that?

 int place_value(int value, int base, int place) { int value_in_place= value; for (int place_index= 1; place_index<place; ++place_index) { value_in_place/=base; } return value_in_place % base; } 

where place is an index based on one of the numbers you want on the right.

+1
source

The following method, placeValue, returns char , since bases 11-36 have digits greater than 9. The method expects:

  • int value: integer value
  • int base: a base of numbers to convert the integer to; valid values โ€‹โ€‹are 2-36
  • int place: index of the digit; least significant digit has index 1

 import java.math.BigInteger; ... private static char placeValue(int value, int base, int place) { BigInteger bigValue = BigInteger.valueOf(value); String baseString = bigValue.toString(base); int numDigits = baseString.length(); int digitIndex = numDigits - place; char digit = baseString.charAt(digitIndex); return digit; } 
0
source

All Articles