/    Sign up×
Community /Pin to ProfileBookmark

String to binary simpler than this?

I found this function the simplest to convert from binary to string

“`
function bin2text(bin) {
return (String.fromCharCode(…bin.split(‘ ‘).map(bin => parseInt(bin, 2))));
}
“`

But could the opposite (string to binary) also be simplified as above?

“`
function text2bin(str) {
return str.split(”).map(function(str) {
return str.charCodeAt(0).toString(2);
});
}
“`

https://jsfiddle.net/dyr1j8gp/2/

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@sibertauthorNov 11.2022 — ["string to binary simple?","String to binary simpler than this?"]
Copy linkTweet thisAlerts:
@NogDogNov 11.2022 — No suggestions, but...

  • 1. I'm just curious why you'd want to do this? :)

  • 2. Just playing around a bit in JSFiddle, if I try to send the output of the text2bin() function into the bin2text() function, it appears to error (at least no alert pops up).
  • Copy linkTweet thisAlerts:
    @sibertauthorNov 11.2022 — > @NogDog#1648408 I'm just curious why you'd want to do this? 🙂

    I am trying to create a PubSub function using [NATS](https://nats.io). And the NATS server uses only binary messages in Websockets. So I have to convert it back and forth. And as I am learning Javascript, I want to make this code cleaner if possible.

    > Just playing around a bit in JSFiddle, if I try to send the output of the text2bin() function into the bin2text() function, it appears to error (at least no alert pops up).

    Can you elaborate this?

    Binary to String:

    https://jsfiddle.net/5a4gt9dq/

    String to Binary:

    https://jsfiddle.net/dyr1j8gp/2/
    Copy linkTweet thisAlerts:
    @NogDogNov 11.2022 — I just tried to feed the result of one into the other, something like:
    [code=javascript]
    let teststr = 'Hello World'
    let testbin = '01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01100100'

    alert(bin2text(testbin)) // works(?)
    alert(text2bin(teststr)) // works, but has comma separators
    // expect this to output "Hello World", but get no alert:
    alert(bin2text(text2bin(teststr)))

    function bin2text(bin) {
    return (String.fromCharCode(...bin.split(' ').map(bin => parseInt(bin, 2))));
    }

    function text2bin(str) {
    return str.split('').map(function(str) {
    return str.charCodeAt(0).toString(2);
    });
    }
    [/code]
    Copy linkTweet thisAlerts:
    @tracknutNov 11.2022 — > let testbin = '01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01100100'

    I'm no JS expert, but I'm having trouble imagining that his is what JS or NATS (I don't even know what that is) calls "binary". testbin here is a string with ascii characters "0" and "1" in it.

    Or maybe I've missed the point.
    Copy linkTweet thisAlerts:
    @UmairAhmadNov 12.2022 — This article show you how to use Integer. to Binary String or bit masking to convert a string to a binary string representative.

    **Links removed by Site Staff so it doesn't look like you're spamming us. Please don't post them again.**
    Copy linkTweet thisAlerts:
    @sibertauthorNov 12.2022 — > @tracknut#1648414 I'm no JS expert, but I'm having trouble imagining that his is what JS or NATS (I don't even know what that is) calls "binary".

    I do not have the full knowledge either, but binary is not Javascript:

    > All computer data is represented using binary, a number system that uses 0s and 1s. (source Google)

    NATS claims to be a more advanced server and faster server than the Socket.io that could handle PubSub and other types of communication like streaming etc.

    And [NATS](https://github.com/nats-io/nats-server) is not Javascript either. It is a PubSub/Streaming server sort of. That can communicate bidirectly with text to NATS or via binary using the builtin Websocket server (if you use Javascript). From the author:

    > NATS Supports only WebSocket data frames in Binary, not Text format (https://tools.ietf.org/html/rfc6455#section-5.6). The server will always send in Binary and your clients MUST send in Binary too.

    The above means that I have to convert any message to a binary string. And I am searching for a smart, simple and clean way to do this using Javascript.

    I have done a [lame attempt with websocket as a service](https://ws.go4webdev.org) (not using NATS) to understand, but my goal is to work with channels or rooms to serve multiple tenants. And this should NATS do in a simpler way. For an example: **_tasks.mary_** should only notify changes on Marys tasks. _**tasks.***_ should notify all users.
    Copy linkTweet thisAlerts:
    @sibertauthorNov 12.2022 — > @NogDog#1648412 I just tried to feed the result of one into the other, something like:

    It seems that the comma is the problem. Here is another try:

    ``<i>
    </i>function bin2text(bin) {
    return (String.fromCharCode(...bin.split(' ').map(bin =&gt; parseInt(bin, 2))));
    }

    function str2bin(input) {
    let chars = input.split('');
    return chars
    .map(function(char) {
    return char.charCodeAt(0).toString(2).padStart(8, 0)
    })
    .join(' ');
    }
    alert(bin2str(str2bin("Hello World")))<i>
    </i>
    ``

    https://jsfiddle.net/nr39phaz/

    The question remains. Why does str2bin takes more lines of code? Is there a way to reduce the length of the function?
    Copy linkTweet thisAlerts:
    @tracknutNov 12.2022 — > @sibert#1648422 The above means that I have to convert any message to a binary string. And I am searching for a smart, simple and clean way to do this using Javascript.

    "Hello" is a binary string, though. (especially if you agree with your quote from Google stating that all computer data is binary!). From the page you reference:

    Binary

    The "Payload data" is arbitrary binary data whose interpretation
    is solely up to the application layer.

    [/quote]

    In english, this means "stuff anything you want in the payload, we don't touch it."

    5.7. Examples

    o A single-frame unmasked text message

    * 0x81 0x05 0x48 0x65 0x6c 0x6c 0x6f (contains "Hello")
    [/quote]

    So looking at section 5.2 on the framing protocol, those first two bytes (0x81 and 0x05) are 0x81 meaning the FIN bit is set (close the connection after this message), and the opcode is 1, meaning this is a text frame. The second byte (0x05) is the payload length 5, meaning the length of the string "Helllo".

    Then, the following 5 bytes (0x48 0x65 0x6c 0x6c 0x6f) are the ASCII string "Hello".

    So presuming you're trying to format up a message like that, you need the JS code to create the bytes for the framing protocol bytes, and then just append "Hello" to it. Something like:

    str = String.fromCharCode(0x81);

    str += String.fromCharCode(0x05);

    str += "Hello";
    [/quote]

    Now this is un-tested, and like I say I'm no expert in either of the technologies you're using here, but that's where I'd start. Obviously you would package that little snippet a different way than just hardcoding the opcodes and length.
    ×

    Success!

    Help @sibert spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...