Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: Base64 encoding Date: Sat, 14 Mar 2015 10:56:08 +0000 Organization: A noiseless patient Spider Lines: 31 Message-ID: <87sid7u9tj.fsf@bsb.me.uk> References: <0f320550-d218-40ea-9e9b-43a01ab53b6b@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="10772"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19u70yVURrvnwzdkomAS97waXdPkBP6KMs=" Cancel-Lock: sha1:fyu60CXwFeH9YgE42TYYJpyp/eA= sha1:E33mUuIKuE3Qo63HxtFGo9XHqBg= X-BSB-Auth: 1.06d11d2169221b0c9cef.20150314105608GMT.87sid7u9tj.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:27024 jonas.thornvall@gmail.com writes: > There is alot of javascript doing base64 encoding and i have probably > implemented my own, but not recently. > > Could the below logic represent how a conversion could be done. > I do realise it may not be the standard way and more highlevel, > require at least bignumb addition, but would it yield correct > encoding? > > 1. Get the byte values with charCodeAt > 2. Treat the bytevalues from string as base 256. > 3. Convert the base 256 value to base 10. (do not know howto go from > 256 to 64 right out of head) > 4. Convert base 10 into base 64. > 5. Map the characters upon the base 64 encoded. > > Maybe it is wrong? The main error is that the values from charCodeAt are not eight bits wide but up to 16 bits wide, but you also need to take care of the padding issue -- the number of encoded bytes may not be a multiple of three. Obviously the issue is slightly different when encoding 16-bit values. Aside: converting between different bases that are powers of two is just a matter of grouping the bits differently, so it can all done by shifts and bit-wise ands and ors. -- Ben.