[R] Converting binary number to in Two´s complement representation

Paul Bernal p@u|bern@|07 @end|ng |rom gm@||@com
Mon Jan 20 15:36:20 CET 2020


Dear friend Rui,

Hope you are doing great, thanks for your kind feedback. The challenge I
currently have at hand is to decode AIS messages and obtain latitude and
longitude values from those.

So basically, I want to accomplish something like in the example below. I
want to convert this binary number (10110010) into the two´s complement
representation, there is the logic they are using for that. Since longitude
ranges from
Example of conversion to decimal of a signed binary number in two's
complement representation

Let's convert to decimal the following signed binary number: 10110010
10110010 = -1×27 + 0×26 + 1×25 + 1×24 + 0×23 + 0×22 + 1×21 + 0×20 = -128 +
32 + 16 + 2 = -78.

El lun., 20 ene. 2020 a las 7:22, Rui Barradas (<ruipbarradas using sapo.pt>)
escribió:

> Sorry, missunderstood the problem.
> Here it goes:
>
> fun <- function(x){
>    res <- sapply(x, function(y){
>      if(nchar(y) %% 8 != 0 || substr(y, 1, 1) == "0"){
>        strtoi(y, base = 2)
>      }else{
>        y <- unlist(strsplit(y, ""))
>        -sum((y != "1")*2^((length(y) - 1):0)) - 1
>      }
>    })
>    unname(res)
> }
>
> fun("10110010")
> fun("10000000")
> fun(c("01000000", "01111111", "10110010", "10000000"))
>
>
> Hope this helps,
>
> Rui Barradas
>
> Às 11:38 de 20/01/20, Rui Barradas escreveu:
> > Hello,
> >
> > Is this what you want?
> >
> >
> > x <- "10110010"
> > strtoi(x, base = 2)
> > #[1] 178
> >
> >
> > Hope this helps,
> >
> > Rui Barradas
> >
> > Às 16:31 de 16/01/20, Paul Bernal escreveu:
> >> Dear friends,
> >>
> >> How can I convert the following binary number in two´s complement
> >> representation in R?
> >>
> >> 10110010
> >>
> >> Any help and/or guidance will be greatly appreciated,
> >>
> >> Best regards,
> >>
> >> Paul
> >>
> >>     [[alternative HTML version deleted]]
> >>
> >> ______________________________________________
> >> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> >> https://stat.ethz.ch/mailman/listinfo/r-help
> >> PLEASE do read the posting guide
> >> http://www.R-project.org/posting-guide.html
> >> and provide commented, minimal, self-contained, reproducible code.
> >>
> >
> > ______________________________________________
> > R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list