Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #29407

Re: How do I convert the following to Uint8Array.

From Stefan Weiss <krewecherl@gmail.com>
Newsgroups comp.lang.javascript
Subject Re: How do I convert the following to Uint8Array.
Date 2016-01-22 14:22 +0100
Organization albasani.net
Message-ID <n7taev$uh4$1@news.albasani.net> (permalink)
References <ce4bb039-aa19-4cbe-bb9b-8b8f004f8992@googlegroups.com> <n7t74i$obt$1@news.albasani.net> <n7t7hq$p6i$1@news.albasani.net> <87powtwz8x.fsf@bsb.me.uk>

Show all headers | View raw


On 01/22/2016 13:54, Ben Bacarisse wrote:
> Stefan Weiss <krewecherl@gmail.com> writes:
>>   var str = "ab05d705";
>>   var arr = Uint8Array.from(
>>     str.match(/../g).map(function (hex) { return parseInt(hex, 16); })
>>   );
> 
> I didn't think of using match -- much nicer!  You can avoid using map if
> you like because 'from' allows for a mapping function:
> 
>   Uint8Array.from(s.match(/../g), d => parseInt(d, 16))
> 
> or even
> 
>   Uint8Array.from(s.match(/../g), d => '0x'+d)
> 
> but I think the explicit parseInt is more helpful.

Ooh, I didn't know about the callback in Uint8Array.from().
That's very useful :)

For the record, here's the bitwise thing I mentioned earlier. It's not
as flexible and rather ugly, but it does the job if the input doesn't
exceed four bytes:

    var num = parseInt(str, 16);
    var arr = Uint8Array.from([
        (num >> 24) & 0xff,
        (num >> 16) & 0xff,
        (num >>  8) & 0xff,
        num & 0xff
    ]);

- stefan

Back to comp.lang.javascript | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How do I convert the following to Uint8Array. Robby Balona <robby@grab.co.za> - 2016-01-22 03:52 -0800
  Re: How do I convert the following to Uint8Array. Stefan Weiss <krewecherl@gmail.com> - 2016-01-22 13:25 +0100
    Re: How do I convert the following to Uint8Array. Stefan Weiss <krewecherl@gmail.com> - 2016-01-22 13:32 +0100
      Re: How do I convert the following to Uint8Array. Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-01-22 12:54 +0000
        Re: How do I convert the following to Uint8Array. Stefan Weiss <krewecherl@gmail.com> - 2016-01-22 14:22 +0100
  Re: How do I convert the following to Uint8Array. Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-01-22 12:41 +0000
  Re: How do I convert the following to Uint8Array. Robby Balona <robby@grab.co.za> - 2016-01-23 00:51 -0800
    Re: How do I convert the following to Uint8Array. Stefan Weiss <krewecherl@gmail.com> - 2016-01-23 12:15 +0100
    Re: How do I convert the following to Uint8Array. Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-01-23 11:17 +0000
  Re: How do I convert the following to Uint8Array. Robby Balona <robby@grab.co.za> - 2016-01-24 09:44 -0800

csiph-web