Reputation: 59
I need to convert the data format of an int16 to a string representing its hexadecimal value.
I have tried some hex converters but they change the data instead of changing the formatting. I need it to be a string representation of its hexadecimal value.
data := (data from buffer)
fmt.Printf("BUFFER DATA : %X\n", data) // output print on screen D9DC (hex)
fmt.Println(("BUFFER DATA : ", string(data)) // output print on screen 55772 (dec)
fmt.Println(("BUFFER DATA : ", data) // output print on screen [?]
How can I convert the data format so it prints D9DC
with fmt.Println
?
Full code here https://play.golang.org/p/WVpMb9lh1Rx
Upvotes: 0
Views: 760
Reputation: 3734
Since fmt.Println
doesn't accept format flags, it prints each variable depending on its type.
crc16.Checksum
returns an int16, so fmt.Println
will display the integer value of your hexadecimal string, which is 55772
.
If you want fmt.Println
to print D9DC
instead of the integer value, you have multiple choices.
String()
method, which is an integer but is represented by its hexadecimal value when printed.For the second option, your type could be something like this:
type Hex int16
func (h Hex) String() string {
return strconv.FormatInt(int64(h), 16)
}
fmt.Println
will automatically use this method because it means the Hex
type implements the Stringer
interface. For more info on this, here are some resources:
Upvotes: 2