Can I convert a byte as a string into a real byte?

50 views
Skip to first unread message

P THE AWESOME

unread,
Dec 3, 2014, 9:36:53 PM12/3/14
to nod...@googlegroups.com
I am trying to convert a string with the byte number in it into a real byte.

var string = "23"; // Or it could be 4E, CA, 22, FF, or any other byte
var byte = somehowConvertStringToByte(string); // The variable "byte" Should look like 0x23 to NodeJS
var otherByte = 0x23; // This is 100% equal to the variable "byte." NodeJS will see this variable and "byte" the exact same way.

Hopefully this makes sense. I'm have to generate some stupid checksums to get my UPB serial PIM to accept commands. I have the reset of the code working. I'm making a CLI script that generates UPB commands and then sends them with node-serialport.

Thank you for any help, as this has completely stumped me.

Athiwat

unread,
Dec 4, 2014, 10:40:17 AM12/4/14
to nod...@googlegroups.com
This parseInt() something you want?
Try parseInt("23", 16)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

I'm on mobile, if anything is incorrect then sorry.

--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/90d6eac1-bfff-4ded-8bef-bed54b8634ee%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Aria Stewart

unread,
Dec 4, 2014, 10:40:20 AM12/4/14
to nod...@googlegroups.com
Try this:

parseInt(string.slice(0,2), 16)

string.slice(0, 2) grabs the first two characters: two nybbles, one byte.

parseInt(str, 16) parses that into a native Number, assuming base 16 (hexadecimal, like your example)

0x23 is a literal for a Number, so that, too, makes a value that is equal to what that returns.

Aria

P THE AWESOME

unread,
Dec 4, 2014, 12:23:43 PM12/4/14
to nod...@googlegroups.com
Thank you so much. parseInt(string.slice(0,2), 16) worked perfectly!
Reply all
Reply to author
Forward
0 new messages