B4J Question is this code b4xable?

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
so i tried but failed miserably, mainly because i am not used to work with bytes.

say i have 4 byte octets that i want to convert to a single long
B4X:
        long result = 0;
        for (byte octet : octets) {
            result <<= 8;
            result |= octet & 0xff;
        }
        return result;

tried

B4X:
dim result as long = 0
for each octet as byte in octets
    result = bit.shiftleftlong(result,8)
    result = bit.or(result,octet & 0xff)
next
return result
 
Solution

is this code b4xable?​

Always yes.

Two ways:
B4X:
Sub AppStart (Args() As String)
    Dim bc As ByteConverter
    Dim octets() As Byte = Array As Byte(1, 2, 3, 4, 5, 6, 7, 8)
    Dim longs() As Long = bc.LongsFromBytes(octets)
    Log(longs(0))
    Log(OctetsToLong(octets))
End Sub

Private Sub OctetsToLong(Octets() As Byte) As Long
    Dim res As Long
    For Each oct As Byte In Octets
        res = Bit.ShiftLeftLong(res, 8)
        res = Bit.OrLong(res, Bit.And(0xff, oct))
    Next
    Return res
End Sub

Erel

B4X founder
Staff member
Licensed User
Longtime User

is this code b4xable?​

Always yes.

Two ways:
B4X:
Sub AppStart (Args() As String)
    Dim bc As ByteConverter
    Dim octets() As Byte = Array As Byte(1, 2, 3, 4, 5, 6, 7, 8)
    Dim longs() As Long = bc.LongsFromBytes(octets)
    Log(longs(0))
    Log(OctetsToLong(octets))
End Sub

Private Sub OctetsToLong(Octets() As Byte) As Long
    Dim res As Long
    For Each oct As Byte In Octets
        res = Bit.ShiftLeftLong(res, 8)
        res = Bit.OrLong(res, Bit.And(0xff, oct))
    Next
    Return res
End Sub
 
Upvote 0
Solution
Cookies are required to use this site. You must accept them to continue using the site. Learn more…