Domanda

I'm trying to figure out how to make base conversion (base 36) use 0 as first character.

I want to represent positive integers using a scheme where 1 is represented as 0, 10 is represented as 9, 11 is represented as a, and so own, where leading zeroes are significant.

So convert(36) should give me z and then convert(37) should give me 00.

I figured that this format is similar enough to base 36 that I should be able to use base_convert to do it, but I haven't been able to figure out how.

È stato utile?

Soluzione

Here is a function that does the conversion the way you want. It could probably be done a lot more efficiently, but at least this gets it done:

function base_convert_0($number, $from_base, $to_base){
    $numeric = base_convert($number, $from_base, 10);

    $result = ''; 
    while($numeric > $to_base){
        $result = base_convert(($numeric - 1) % $to_base, 10, 36) . $result;

        $numeric = floor(($numeric - 1)/$to_base);
    }   
    $result = base_convert(($numeric - 1), 10, 36) . $result;

    return $result;
}

5000 lines of output

80 lines shown here (base_convert_0($i, 10, 36)):

1: 0
2: 1
3: 2
4: 3
5: 4
6: 5
7: 6
8: 7
9: 8
10: 9
11: a
12: b
13: c
14: d
15: e
16: f
17: g
18: h
19: i
20: j
21: k
22: l
23: m
24: n
25: o
26: p
27: q
28: r
29: s
30: t
31: u
32: v
33: w
34: x
35: y
36: z
37: 00
38: 01
39: 02
40: 03
41: 04
42: 05
43: 06
44: 07
45: 08
46: 09
47: 0a
48: 0b
49: 0c
50: 0d
51: 0e
52: 0f
53: 0g
54: 0h
55: 0i
56: 0j
57: 0k
58: 0l
59: 0m
60: 0n
61: 0o
62: 0p
63: 0q
64: 0r
65: 0s
66: 0t
67: 0u
68: 0v
69: 0w
70: 0x
71: 0y
72: 0z
73: 10
74: 11
75: 12
76: 13
77: 14
78: 15
79: 16
80: 17

I'm not sure if you need to reverse this, but that's the easy part anyway:

function base_convert_un0($number, $from_base, $to_base){
    $as_string = strval($number);
    for($result = $j = 0, $i = strlen($as_string); $i--; $j++)
        $result += (base_convert($as_string{$i}, $from_base, 10) + 1)*pow($from_base, $j);
    return base_convert($result, 10, $to_base);
}

Altri suggerimenti

I don't really understand the point of your transformation, but don't you just try to convert n-1?

base_convert ($number_to_convert - 1, 10, 36);

EDIT: If 1base 10 transforms to 0your special base – what character will you use for 0? I don't think your system can be used for valid notations of numbers.

EDIT2: I've probably understood the question in a too mathematical way. Please refer to @Paulpro's answer for a pragmatic solution to the problem (that isn't actually converting to another base but returning a string representing the input number).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top