Convert MAC Address to Decimal string.

3,372 views
Skip to first unread message

Rich

unread,
Feb 1, 2011, 4:01:16 PM2/1/11
to golang-nuts
I am porting a Ruby application into a Go application, and need to
convert a MAC address into Decimal string. This script converts
millions of lines of text into CSV, and one of the fields is a HEX Mac
address, and it needs a conversion to Decimal. The reason for the
port is for speed. The ruby script runs a 24MB file of 24k lines in 9
seconds, Go does it in 3.

In Ruby you can convert a Mac address into a decmal using the
following Code:

mac="00-15-CF-80-F8-13"
# Strip '-' from string:
mac=mac.gsub(/-/,'')
# convert to decimal:
mac=mac.hex

In IRB this looks like:

irb(main):001:0> mac="00-15-CF-80-F8-13"
=> "00-15-CF-80-F8-13"
irb(main):002:0> # Strip '-' from string:
irb(main):003:0* mac=mac.gsub(/-/,'')
=> "0015CF80F813"
irb(main):004:0> # convert to decimal:
irb(main):005:0* mac=mac.hex
=> 93675649043
irb(main):006:0>

How can I do this in Go?

Evan Shaw

unread,
Feb 1, 2011, 4:12:07 PM2/1/11
to Rich, golang-nuts
On Wed, Feb 2, 2011 at 10:01 AM, Rich <rma...@gmail.com> wrote:
> In Ruby you can convert a Mac address into a decmal using the
> following Code:
>
> mac="00-15-CF-80-F8-13"
> # Strip '-' from string:
> mac=mac.gsub(/-/,'')
> # convert to decimal:
> mac=mac.hex
>
> How can I do this in Go?
>

It would look something like this:

mac := "00-15-CF-80-F8-13"
mac = strings.Replace(mac, "-", "", -1) // the last argument could be 5 instead
decMac := strconv.Btoui64(mac, 16)

And of course you have to put this in some function and import the
correct packages, but I'll leave that to you.

- Evan

Rich

unread,
Feb 1, 2011, 6:11:11 PM2/1/11
to golang-nuts
Evan,

Thank you for that bit of code!!!

For all those interested here is the finished code snippet that can be
run as a stand alone example. Of course I'll integrate it into my
other code, but it will give others the idea of how to do this in the
future. For all those who may not have figured it out, but a lot of
go code has error checking built in, and in my final code I'd rewrite
this line
"decMac,_ :=strconv.Btoi64(mac,16)"
to read:
"decMac,err:=strconv.Btoi64(mac,16)"


That way I can perform a quick error check on the err variable.
------------------------------------------------------
package main

import (
"strings"
"strconv"
)

func main() {
mac:="00-15-CF-80-F8-13"
mac = strings.Replace(mac,"-","",-1)
decMac,_ :=strconv.Btoi64(mac,16)
println(mac," to ",decMac)
}
------------------------------------------------------
Reply all
Reply to author
Forward
0 new messages