Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中转换为base 42(Convert to base 42 in javascript)

I want convert a integer form base 10 to base 42 in Javascript,(我想将整数从10转换为Java的42)

by default Javascript can do to base 36 not more.(默认情况下,Javascript的基数不能超过36。) How can I do to resolve this problem ?(如何解决此问题?)   ask by TheDevGuy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To begin you need some sort of symbol system to represent digits.(首先,您需要某种符号系统来表示数字。)

In base 10 we have 10: 0 - 9 .(在以10为底的基础上,我们有10: 0 - 9 。) In base 16 you have 16 0 - 9 and A – F .(在基数16中,您有16 0 - 9A – F) Binary, of course you only have 2: 0 and 1 .(二进制,当然只有2: 01 。) So for base 42 you'll need 42 types of digit.(因此,对于以42为底的数字,您将需要42种数字。) Since this just seems like an exercise maybe include upper and lower case digits (I'm sure there's a better scheme if you put your mind to it):(由于这似乎是一个练习,可能包含大写和小写数字(如果您下定决心,我敢肯定会有更好的方案):) const symbols = "0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f".split(" ") So the numbers 0 - 41 will be 0 through f .(因此,数字0-41将是0f 。) 42 will start at 10 42**2 will be 100 etc.(42从10开始42 ** 2将是100等等) To get the right-most digit, you can can take the number modulus the base.(要获得最右边的数字,可以将数字模数作为底数。) Then divide by the base (and take the floor) and do it again until your number is reduced to zero.(然后除以基数(并取下地板),然后再次进行直到您的数字减为零。) With the above scheme here is counting to 100 base 42:(通过上述方案,此处以100为底数42:) const symbols = "0 1 2 3 4 5 6 7 8 9 ABCDEFGHIJKLMNOPQRSTU VWXYZ abcdef".split(" ") function toBase(n, base){ if (n === 0 ) return symbols[n] res = "" while (n) { res = symbols[n % base] + res n = Math.floor(n / base) } return res } console.log(Array.from({length: 100}, (_, i) => toBase(i, 42)).join(", "))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...